from IPython.display import display, Markdown
import numpy as np
On a vu des façons de traiter des documents vus comme des sacs des mots en les représentant comme des vecteurs dont les coordonnées correspondaient à des nombres d'occurrences.
Mais on aimerait — entre autres — pouvoir travailler avec des représentations arbitraires, on peut par exemple imaginer vouloir représenter un document par ŀa polarité (au sens de l'analyse du sentiment) de ses mots.
À l'aide d'un lexique de sentiment (par exemple VADER), écrivez une fonction qui prend en entrée un texte en anglais et renvoie sa représentation sous forme d'un vecteur de features à deux traits : polarité positive moyenne (la somme des polarités positives des mots qu'il contient divisée par sa longueur en nombre de mots) et polarité négative moyenne.
def read_vader(vader_path):
pass # À vous de jouer
def featurize(doc, lexicon):
pass # À vous de jouer !
lexicon = read_vader("../../data/vader_lexicon.txt")
doc = "I came in in the middle of this film so I had no idea about any credits or even its title till I looked it up here, where I see that it has received a mixed reception by your commentators. I'm on the positive side regarding this film but one thing really caught my attention as I watched: the beautiful and sensitive score written in a Coplandesque Americana style. My surprise was great when I discovered the score to have been written by none other than John Williams himself. True he has written sensitive and poignant scores such as Schindler's List but one usually associates his name with such bombasticities as Star Wars. But in my opinion what Williams has written for this movie surpasses anything I've ever heard of his for tenderness, sensitivity and beauty, fully in keeping with the tender and lovely plot of the movie. And another recent score of his, for Catch Me if You Can, shows still more wit and sophistication. As to Stanley and Iris, I like education movies like How Green was my Valley and Konrack, that one with John Voigt and his young African American charges in South Carolina, and Danny deVito's Renaissance Man, etc. They tell a necessary story of intellectual and spiritual awakening, a story which can't be told often enough. This one is an excellent addition to that genre."
doc_features = featurize(doc, lexicon)
doc_features
On commence par recycler notre tokenizer/normaliseur
import re
def poor_mans_tokenizer_and_normalizer(s):
return [w.lower() for w in re.split(r"\s|\W", s.strip()) if w and all(c.isalpha() for c in w)]
On lit le lexique
def read_vader(vader_path):
res = dict()
with open(vader_path) as in_stream:
for row in in_stream:
word, polarity, *_ = row.lstrip().split("\t", maxsplit=2)
res[word] = float(polarity)
return res
lexicon = read_vader("../../data/vader_lexicon.txt")
lexicon
{'$:': -1.5,
'%)': -0.4,
'%-)': -1.5,
'&-:': -0.4,
'&:': -0.7,
"( '}{' )": 1.6,
'(%': -0.9,
"('-:": 2.2,
"(':": 2.3,
'((-:': 2.1,
'(*': 1.1,
'(-%': -0.7,
'(-*': 1.3,
'(-:': 1.6,
'(-:0': 2.8,
'(-:<': -0.4,
'(-:o': 1.5,
'(-:O': 1.5,
'(-:{': -0.1,
'(-:|>*': 1.9,
'(-;': 1.3,
'(-;|': 2.1,
'(8': 2.6,
'(:': 2.2,
'(:0': 2.4,
'(:<': -0.2,
'(:o': 2.5,
'(:O': 2.5,
'(;': 1.1,
'(;<': 0.3,
'(=': 2.2,
'(?:': 2.1,
'(^:': 1.5,
'(^;': 1.5,
'(^;0': 2.0,
'(^;o': 1.9,
'(o:': 1.6,
")':": -2.0,
")-':": -2.1,
')-:': -2.1,
')-:<': -2.2,
')-:{': -2.1,
'):': -1.8,
'):<': -1.9,
'):{': -2.3,
');<': -2.6,
'*)': 0.6,
'*-)': 0.3,
'*-:': 2.1,
'*-;': 2.4,
'*:': 1.9,
'*<|:-)': 1.6,
'*\\0/*': 2.3,
'*^:': 1.6,
',-:': 1.2,
"---'-;-{@": 2.3,
'--<--<@': 2.2,
'.-:': -1.2,
'..###-:': -1.7,
'..###:': -1.9,
'/-:': -1.3,
'/:': -1.3,
'/:<': -1.4,
'/=': -0.9,
'/^:': -1.0,
'/o:': -1.4,
'0-8': 0.1,
'0-|': -1.2,
'0:)': 1.9,
'0:-)': 1.4,
'0:-3': 1.5,
'0:03': 1.9,
'0;^)': 1.6,
'0_o': -0.3,
'10q': 2.1,
'1337': 2.1,
'143': 3.2,
'1432': 2.6,
'14aa41': 2.4,
'182': -2.9,
'187': -3.1,
'2g2b4g': 2.8,
'2g2bt': -0.1,
'2qt': 2.1,
'3:(': -2.2,
'3:)': 0.5,
'3:-(': -2.3,
'3:-)': -1.4,
'4col': -2.2,
'4q': -3.1,
'5fs': 1.5,
'8)': 1.9,
'8-d': 1.7,
'8-o': -0.3,
'86': -1.6,
'8d': 2.9,
':###..': -2.4,
':$': -0.2,
':&': -0.6,
":'(": -2.2,
":')": 2.3,
":'-(": -2.4,
":'-)": 2.7,
':(': -1.9,
':)': 2.0,
':*': 2.5,
':-###..': -2.5,
':-&': -0.5,
':-(': -1.5,
':-)': 1.3,
':-))': 2.8,
':-*': 1.7,
':-,': 1.1,
':-.': -0.9,
':-/': -1.2,
':-<': -1.5,
':-d': 2.3,
':-D': 2.3,
':-o': 0.1,
':-p': 1.5,
':-[': -1.6,
':-\\': -0.9,
':-c': -1.3,
':-|': -0.7,
':-||': -2.5,
':-Þ': 0.9,
':/': -1.4,
':3': 2.3,
':<': -2.1,
':>': 2.1,
':?)': 1.3,
':?c': -1.6,
':@': -2.5,
':d': 2.3,
':D': 2.3,
':l': -1.7,
':o': -0.4,
':p': 1.0,
':s': -1.2,
':[': -2.0,
':\\': -1.3,
':]': 2.2,
':^)': 2.1,
':^*': 2.6,
':^/': -1.2,
':^\\': -1.0,
':^|': -1.0,
':c': -2.1,
':c)': 2.0,
':o)': 2.1,
':o/': -1.4,
':o\\': -1.1,
':o|': -0.6,
':P': 1.4,
':{': -1.9,
':|': -0.4,
':}': 2.1,
':Þ': 1.1,
';)': 0.9,
';-)': 1.0,
';-*': 2.2,
';-]': 0.7,
';d': 0.8,
';D': 0.8,
';]': 0.6,
';^)': 1.4,
'</3': -3.0,
'<3': 1.9,
'<:': 2.1,
'<:-|': -1.4,
'=)': 2.2,
'=-3': 2.0,
'=-d': 2.4,
'=-D': 2.4,
'=/': -1.4,
'=3': 2.1,
'=d': 2.3,
'=D': 2.3,
'=l': -1.2,
'=\\': -1.2,
'=]': 1.6,
'=p': 1.3,
'=|': -0.8,
'>-:': -2.0,
'>.<': -1.3,
'>:': -2.1,
'>:(': -2.7,
'>:)': 0.4,
'>:-(': -2.7,
'>:-)': -0.4,
'>:/': -1.6,
'>:o': -1.2,
'>:p': 1.0,
'>:[': -2.1,
'>:\\': -1.7,
'>;(': -2.9,
'>;)': 0.1,
'>_>^': 2.1,
'@:': -2.1,
'@>-->--': 2.1,
"@}-;-'---": 2.2,
'aas': 2.5,
'aayf': 2.7,
'afu': -2.9,
'alol': 2.8,
'ambw': 2.9,
'aml': 3.4,
'atab': -1.9,
'awol': -1.3,
'ayc': 0.2,
'ayor': -1.2,
'aug-00': 0.3,
'bfd': -2.7,
'bfe': -2.6,
'bff': 2.9,
'bffn': 1.0,
'bl': 2.3,
'bsod': -2.2,
'btd': -2.1,
'btdt': -0.1,
'bz': 0.4,
'b^d': 2.6,
'cwot': -2.3,
"d-':": -2.5,
'd8': -3.2,
'd:': 1.2,
'd:<': -3.2,
'd;': -2.9,
'd=': 1.5,
'doa': -2.3,
'dx': -3.0,
'ez': 1.5,
'fav': 2.0,
'fcol': -1.8,
'ff': 1.8,
'ffs': -2.8,
'fkm': -2.4,
'foaf': 1.8,
'ftw': 2.0,
'fu': -3.7,
'fubar': -3.0,
'fwb': 2.5,
'fyi': 0.8,
'fysa': 0.4,
'g1': 1.4,
'gg': 1.2,
'gga': 1.7,
'gigo': -0.6,
'gj': 2.0,
'gl': 1.3,
'gla': 2.5,
'gn': 1.2,
'gr8': 2.7,
'grrr': -0.4,
'gt': 1.1,
'h&k': 2.3,
'hagd': 2.2,
'hagn': 2.2,
'hago': 1.2,
'hak': 1.9,
'hand': 2.2,
'heart': 3.2,
'hearts': 3.3,
'hho1/2k': 1.4,
'hhoj': 2.0,
'hhok': 0.9,
'hugz': 2.0,
'hi5': 1.9,
'idk': -0.4,
'ijs': 0.7,
'ilu': 3.4,
'iluaaf': 2.7,
'ily': 3.4,
'ily2': 2.6,
'iou': 0.7,
'iyq': 2.3,
'j/j': 2.0,
'j/k': 1.6,
'j/p': 1.4,
'j/t': -0.2,
'j/w': 1.0,
'j4f': 1.4,
'j4g': 1.7,
'jho': 0.8,
'jhomf': 1.0,
'jj': 1.0,
'jk': 0.9,
'jp': 0.8,
'jt': 0.9,
'jw': 1.6,
'jealz': -1.2,
'k4y': 2.3,
'kfy': 2.3,
'kia': -3.2,
'kk': 1.5,
'kmuf': 2.2,
'l': 2.0,
'l&r': 2.2,
'laoj': 1.3,
'lmao': 2.9,
'lmbao': 1.8,
'lmfao': 2.5,
'lmso': 2.7,
'lol': 1.8,
'lolz': 2.7,
'lts': 1.6,
'ly': 2.6,
'ly4e': 2.7,
'lya': 3.3,
'lyb': 3.0,
'lyl': 3.1,
'lylab': 2.7,
'lylas': 2.6,
'lylb': 1.6,
'm8': 1.4,
'mia': -1.2,
'mml': 2.0,
'mofo': -2.4,
'muah': 2.3,
'mubar': -1.0,
'musm': 0.9,
'mwah': 2.5,
'n1': 1.9,
'nbd': 1.3,
'nbif': -0.5,
'nfc': -2.7,
'nfw': -2.4,
'nh': 2.2,
'nimby': -0.8,
'nimjd': -0.7,
'nimq': -0.2,
'nimy': -1.4,
'nitl': -1.5,
'nme': -2.1,
'noyb': -0.7,
'np': 1.4,
'ntmu': 1.4,
'o-8': -0.5,
'o-:': -0.3,
'o-|': -1.1,
'o.o': -0.8,
'O.o': -0.6,
'o.O': -0.6,
'o:': -0.2,
'o:)': 1.5,
'o:-)': 2.0,
'o:-3': 2.2,
'o:3': 2.3,
'o:<': -0.3,
'o;^)': 1.6,
'ok': 1.2,
'o_o': -0.5,
'O_o': -0.5,
'o_O': -0.5,
'pita': -2.4,
'pls': 0.3,
'plz': 0.3,
'pmbi': 0.8,
'pmfji': 0.3,
'pmji': 0.7,
'po': -2.6,
'ptl': 2.6,
'pu': -1.1,
'qq': -2.2,
'qt': 1.8,
'r&r': 2.4,
'rofl': 2.7,
'roflmao': 2.5,
'rotfl': 2.6,
'rotflmao': 2.8,
'rotflmfao': 2.5,
'rotflol': 3.0,
'rotgl': 2.9,
'rotglmao': 1.8,
's:': -1.1,
'sapfu': -1.1,
'sete': 2.8,
'sfete': 2.7,
'sgtm': 2.4,
'slap': 0.6,
'slaw': 2.1,
'smh': -1.3,
'snafu': -2.5,
'sob': -1.0,
'swak': 2.3,
'tgif': 2.3,
'thks': 1.4,
'thx': 1.5,
'tia': 2.3,
'tmi': -0.3,
'tnx': 1.1,
'true': 1.8,
'tx': 1.5,
'txs': 1.1,
'ty': 1.6,
'tyvm': 2.5,
'urw': 1.9,
'vbg': 2.1,
'vbs': 3.1,
'vip': 2.3,
'vwd': 2.6,
'vwp': 2.1,
'wag': -0.2,
'wd': 2.7,
'wilco': 0.9,
'wp': 1.0,
'wtf': -2.8,
'wtg': 2.1,
'wth': -2.4,
'x-d': 2.6,
'x-p': 1.7,
'xd': 2.8,
'xlnt': 3.0,
'xoxo': 3.0,
'xoxozzz': 2.3,
'xp': 1.6,
'xqzt': 1.6,
'xtc': 0.8,
'yolo': 1.1,
'yoyo': 0.4,
'yvw': 1.6,
'yw': 1.8,
'ywia': 2.5,
'zzz': -1.2,
'[-;': 0.5,
'[:': 1.3,
'[;': 1.0,
'[=': 1.7,
'\\-:': -1.0,
'\\:': -1.0,
'\\:<': -1.7,
'\\=': -1.1,
'\\^:': -1.3,
'\\o/': 2.2,
'\\o:': -1.2,
']-:': -2.1,
']:': -1.6,
']:<': -2.5,
'^<_<': 1.4,
'^urs': -2.8,
'abandon': -1.9,
'abandoned': -2.0,
'abandoner': -1.9,
'abandoners': -1.9,
'abandoning': -1.6,
'abandonment': -2.4,
'abandonments': -1.7,
'abandons': -1.3,
'abducted': -2.3,
'abduction': -2.8,
'abductions': -2.0,
'abhor': -2.0,
'abhorred': -2.4,
'abhorrent': -3.1,
'abhors': -2.9,
'abilities': 1.0,
'ability': 1.3,
'aboard': 0.1,
'absentee': -1.1,
'absentees': -0.8,
'absolve': 1.2,
'absolved': 1.5,
'absolves': 1.3,
'absolving': 1.6,
'abuse': -3.2,
'abused': -2.3,
'abuser': -2.6,
'abusers': -2.6,
'abuses': -2.6,
'abusing': -2.0,
'abusive': -3.2,
'abusively': -2.8,
'abusiveness': -2.5,
'abusivenesses': -3.0,
'accept': 1.6,
'acceptabilities': 1.6,
'acceptability': 1.1,
'acceptable': 1.3,
'acceptableness': 1.3,
'acceptably': 1.5,
'acceptance': 2.0,
'acceptances': 1.7,
'acceptant': 1.6,
'acceptation': 1.3,
'acceptations': 0.9,
'accepted': 1.1,
'accepting': 1.6,
'accepts': 1.3,
'accident': -2.1,
'accidental': -0.3,
'accidentally': -1.4,
'accidents': -1.3,
'accomplish': 1.8,
'accomplished': 1.9,
'accomplishes': 1.7,
'accusation': -1.0,
'accusations': -1.3,
'accuse': -0.8,
'accused': -1.2,
'accuses': -1.4,
'accusing': -0.7,
'ache': -1.6,
'ached': -1.6,
'aches': -1.0,
'achievable': 1.3,
'aching': -2.2,
'acquit': 0.8,
'acquits': 0.1,
'acquitted': 1.0,
'acquitting': 1.3,
'acrimonious': -1.7,
'active': 1.7,
'actively': 1.3,
'activeness': 0.6,
'activenesses': 0.8,
'actives': 1.1,
'adequate': 0.9,
'admirability': 2.4,
'admirable': 2.6,
'admirableness': 2.2,
'admirably': 2.5,
'admiral': 1.3,
'admirals': 1.5,
'admiralties': 1.6,
'admiralty': 1.2,
'admiration': 2.5,
'admirations': 1.6,
'admire': 2.1,
'admired': 2.3,
'admirer': 1.8,
'admirers': 1.7,
'admires': 1.5,
'admiring': 1.6,
'admiringly': 2.3,
'admit': 0.8,
'admits': 1.2,
'admitted': 0.4,
'admonished': -1.9,
'adopt': 0.7,
'adopts': 0.7,
'adorability': 2.2,
'adorable': 2.2,
'adorableness': 2.5,
'adorably': 2.1,
'adoration': 2.9,
'adorations': 2.2,
'adore': 2.6,
'adored': 1.8,
'adorer': 1.7,
'adorers': 2.1,
'adores': 1.6,
'adoring': 2.6,
'adoringly': 2.4,
'adorn': 0.9,
'adorned': 0.8,
'adorner': 1.3,
'adorners': 0.9,
'adorning': 1.0,
'adornment': 1.3,
'adornments': 0.8,
'adorns': 0.5,
'advanced': 1.0,
'advantage': 1.0,
'advantaged': 1.4,
'advantageous': 1.5,
'advantageously': 1.9,
'advantageousness': 1.6,
'advantages': 1.5,
'advantaging': 1.6,
'adventure': 1.3,
'adventured': 1.3,
'adventurer': 1.2,
'adventurers': 0.9,
'adventures': 1.4,
'adventuresome': 1.7,
'adventuresomeness': 1.3,
'adventuress': 0.8,
'adventuresses': 1.4,
'adventuring': 2.3,
'adventurism': 1.5,
'adventurist': 1.4,
'adventuristic': 1.7,
'adventurists': 1.2,
'adventurous': 1.4,
'adventurously': 1.3,
'adventurousness': 1.8,
'adversarial': -1.5,
'adversaries': -1.0,
'adversary': -0.8,
'adversative': -1.2,
'adversatively': -0.1,
'adversatives': -1.0,
'adverse': -1.5,
'adversely': -0.8,
'adverseness': -0.6,
'adversities': -1.5,
'adversity': -1.8,
'affected': -0.6,
'affection': 2.4,
'affectional': 1.9,
'affectionally': 1.5,
'affectionate': 1.9,
'affectionately': 2.2,
'affectioned': 1.8,
'affectionless': -2.0,
'affections': 1.5,
'afflicted': -1.5,
'affronted': 0.2,
'aggravate': -2.5,
'aggravated': -1.9,
'aggravates': -1.9,
'aggravating': -1.2,
'aggress': -1.3,
'aggressed': -1.4,
'aggresses': -0.5,
'aggressing': -0.6,
'aggression': -1.2,
'aggressions': -1.3,
'aggressive': -0.6,
'aggressively': -1.3,
'aggressiveness': -1.8,
'aggressivities': -1.4,
'aggressivity': -0.6,
'aggressor': -0.8,
'aggressors': -0.9,
'aghast': -1.9,
'agitate': -1.7,
'agitated': -2.0,
'agitatedly': -1.6,
'agitates': -1.4,
'agitating': -1.8,
'agitation': -1.0,
'agitational': -1.2,
'agitations': -1.3,
'agitative': -1.3,
'agitato': -0.1,
'agitator': -1.4,
'agitators': -2.1,
'agog': 1.9,
'agonise': -2.1,
'agonised': -2.3,
'agonises': -2.4,
'agonising': -1.5,
'agonize': -2.3,
'agonized': -2.2,
'agonizes': -2.3,
'agonizing': -2.7,
'agonizingly': -2.3,
'agony': -1.8,
'agree': 1.5,
'agreeability': 1.9,
'agreeable': 1.8,
'agreeableness': 1.8,
'agreeablenesses': 1.3,
'agreeably': 1.6,
'agreed': 1.1,
'agreeing': 1.4,
'agreement': 2.2,
'agreements': 1.1,
'agrees': 0.8,
'alarm': -1.4,
'alarmed': -1.4,
'alarming': -0.5,
'alarmingly': -2.6,
'alarmism': -0.3,
'alarmists': -1.1,
'alarms': -1.1,
'alas': -1.1,
'alert': 1.2,
'alienation': -1.1,
'alive': 1.6,
'allergic': -1.2,
'allow': 0.9,
'alone': -1.0,
'alright': 1.0,
'amaze': 2.5,
'amazed': 2.2,
'amazedly': 2.1,
'amazement': 2.5,
'amazements': 2.2,
'amazes': 2.2,
'amazing': 2.8,
'amazon': 0.7,
'amazonite': 0.2,
'amazons': -0.1,
'amazonstone': 1.0,
'amazonstones': 0.2,
'ambitious': 2.1,
'ambivalent': 0.5,
'amor': 3.0,
'amoral': -1.6,
'amoralism': -0.7,
'amoralisms': -0.7,
'amoralities': -1.2,
'amorality': -1.5,
'amorally': -1.0,
'amoretti': 0.2,
'amoretto': 0.6,
'amorettos': 0.3,
'amorino': 1.2,
'amorist': 1.6,
'amoristic': 1.0,
'amorists': 0.1,
'amoroso': 2.3,
'amorous': 1.8,
'amorously': 2.3,
'amorousness': 2.0,
'amorphous': -0.2,
'amorphously': 0.1,
'amorphousness': 0.3,
'amort': -2.1,
'amortise': 0.5,
'amortised': -0.2,
'amortises': 0.1,
'amortizable': 0.5,
'amortization': 0.6,
'amortizations': 0.2,
'amortize': -0.1,
'amortized': 0.8,
'amortizes': 0.6,
'amortizing': 0.8,
'amusable': 0.7,
'amuse': 1.7,
'amused': 1.8,
'amusedly': 2.2,
'amusement': 1.5,
'amusements': 1.5,
'amuser': 1.1,
'amusers': 1.3,
'amuses': 1.7,
'amusia': 0.3,
'amusias': -0.4,
'amusing': 1.6,
'amusingly': 0.8,
'amusingness': 1.8,
'amusive': 1.7,
'anger': -2.7,
'angered': -2.3,
'angering': -2.2,
'angerly': -1.9,
'angers': -2.3,
'angrier': -2.3,
'angriest': -3.1,
'angrily': -1.8,
'angriness': -1.7,
'angry': -2.3,
'anguish': -2.9,
'anguished': -1.8,
'anguishes': -2.1,
'anguishing': -2.7,
'animosity': -1.9,
'annoy': -1.9,
'annoyance': -1.3,
'annoyances': -1.8,
'annoyed': -1.6,
'annoyer': -2.2,
'annoyers': -1.5,
'annoying': -1.7,
'annoys': -1.8,
'antagonism': -1.9,
'antagonisms': -1.2,
'antagonist': -1.9,
'antagonistic': -1.7,
'antagonistically': -2.2,
'antagonists': -1.7,
'antagonize': -2.0,
'antagonized': -1.4,
'antagonizes': -0.5,
'antagonizing': -2.7,
'anti': -1.3,
'anticipation': 0.4,
'anxieties': -0.6,
'anxiety': -0.7,
'anxious': -1.0,
'anxiously': -0.9,
'anxiousness': -1.0,
'aok': 2.0,
'apathetic': -1.2,
'apathetically': -0.4,
'apathies': -0.6,
'apathy': -1.2,
'apeshit': -0.9,
'apocalyptic': -3.4,
'apologise': 1.6,
'apologised': 0.4,
'apologises': 0.8,
'apologising': 0.2,
'apologize': 0.4,
'apologized': 1.3,
'apologizes': 1.5,
'apologizing': -0.3,
'apology': 0.2,
'appall': -2.4,
'appalled': -2.0,
'appalling': -1.5,
'appallingly': -2.0,
'appalls': -1.9,
'appease': 1.1,
'appeased': 0.9,
'appeases': 0.9,
'appeasing': 1.0,
'applaud': 2.0,
'applauded': 1.5,
'applauding': 2.1,
'applauds': 1.4,
'applause': 1.8,
'appreciate': 1.7,
'appreciated': 2.3,
'appreciates': 2.3,
'appreciating': 1.9,
'appreciation': 2.3,
'appreciations': 1.7,
'appreciative': 2.6,
'appreciatively': 1.8,
'appreciativeness': 1.6,
'appreciator': 2.6,
'appreciators': 1.5,
'appreciatory': 1.7,
'apprehensible': 1.1,
'apprehensibly': -0.2,
'apprehension': -2.1,
'apprehensions': -0.9,
'apprehensively': -0.3,
'apprehensiveness': -0.7,
'approval': 2.1,
'approved': 1.8,
'approves': 1.7,
'ardent': 2.1,
'arguable': -1.0,
'arguably': -1.0,
'argue': -1.4,
'argued': -1.5,
'arguer': -1.6,
'arguers': -1.4,
'argues': -1.6,
'arguing': -2.0,
'argument': -1.5,
'argumentative': -1.5,
'argumentatively': -1.8,
'argumentive': -1.5,
'arguments': -1.7,
'arrest': -1.4,
'arrested': -2.1,
'arrests': -1.9,
'arrogance': -2.4,
'arrogances': -1.9,
'arrogant': -2.2,
'arrogantly': -1.8,
'ashamed': -2.1,
'ashamedly': -1.7,
'ass': -2.5,
'assassination': -2.9,
'assassinations': -2.7,
'assault': -2.8,
'assaulted': -2.4,
'assaulting': -2.3,
'assaultive': -2.8,
'assaults': -2.5,
'asset': 1.5,
'assets': 0.7,
'assfucking': -2.5,
'assholes': -2.8,
'assurance': 1.4,
'assurances': 1.4,
'assure': 1.4,
'assured': 1.5,
'assuredly': 1.6,
'assuredness': 1.4,
'assurer': 0.9,
'assurers': 1.1,
'assures': 1.3,
'assurgent': 1.3,
'assuring': 1.6,
'assuror': 0.5,
'assurors': 0.7,
'astonished': 1.6,
'astound': 1.7,
'astounded': 1.8,
'astounding': 1.8,
'astoundingly': 2.1,
'astounds': 2.1,
'attachment': 1.2,
'attachments': 1.1,
'attack': -2.1,
'attacked': -2.0,
'attacker': -2.7,
'attackers': -2.7,
'attacking': -2.0,
'attacks': -1.9,
'attract': 1.5,
'attractancy': 0.9,
'attractant': 1.3,
'attractants': 1.4,
'attracted': 1.8,
'attracting': 2.1,
'attraction': 2.0,
'attractions': 1.8,
'attractive': 1.9,
'attractively': 2.2,
'attractiveness': 1.8,
'attractivenesses': 2.1,
'attractor': 1.2,
'attractors': 1.2,
'attracts': 1.7,
'audacious': 0.9,
'authority': 0.3,
'aversion': -1.9,
'aversions': -1.1,
'aversive': -1.6,
'aversively': -0.8,
'avert': -0.7,
'averted': -0.3,
'averts': -0.4,
'avid': 1.2,
'avoid': -1.2,
'avoidance': -1.7,
'avoidances': -1.1,
'avoided': -1.4,
'avoider': -1.8,
'avoiders': -1.4,
'avoiding': -1.4,
'avoids': -0.7,
'await': 0.4,
'awaited': -0.1,
'awaits': 0.3,
'award': 2.5,
'awardable': 2.4,
'awarded': 1.7,
'awardee': 1.8,
'awardees': 1.2,
'awarder': 0.9,
'awarders': 1.3,
'awarding': 1.9,
'awards': 2.0,
'awesome': 3.1,
'awful': -2.0,
'awkward': -0.6,
'awkwardly': -1.3,
'awkwardness': -0.7,
'axe': -0.4,
'axed': -1.3,
'backed': 0.1,
'backing': 0.1,
'backs': -0.2,
'bad': -2.5,
'badass': 1.4,
'badly': -2.1,
'bailout': -0.4,
'bamboozle': -1.5,
'bamboozled': -1.5,
'bamboozles': -1.5,
'ban': -2.6,
'banish': -1.9,
'bankrupt': -2.6,
'bankster': -2.1,
'banned': -2.0,
'bargain': 0.8,
'barrier': -0.5,
'bashful': -0.1,
'bashfully': 0.2,
'bashfulness': -0.8,
'bastard': -2.5,
'bastardies': -1.8,
'bastardise': -2.1,
'bastardised': -2.3,
'bastardises': -2.3,
'bastardising': -2.6,
'bastardization': -2.4,
'bastardizations': -2.1,
'bastardize': -2.4,
'bastardized': -2.0,
'bastardizes': -1.8,
'bastardizing': -2.3,
'bastardly': -2.7,
'bastards': -3.0,
'bastardy': -2.7,
'battle': -1.6,
'battled': -1.2,
'battlefield': -1.6,
'battlefields': -0.9,
'battlefront': -1.2,
'battlefronts': -0.8,
'battleground': -1.7,
'battlegrounds': -0.6,
'battlement': -0.4,
'battlements': -0.4,
'battler': -0.8,
'battlers': -0.2,
'battles': -1.6,
'battleship': -0.1,
'battleships': -0.5,
'battlewagon': -0.3,
'battlewagons': -0.5,
'battling': -1.1,
'beaten': -1.8,
'beatific': 1.8,
'beating': -2.0,
'beaut': 1.6,
'beauteous': 2.5,
'beauteously': 2.6,
...}
Et voilà comment on récupère la représentation d'un document
def featurize(text, lexicon):
words = poor_mans_tokenizer_and_normalizer(text)
features = np.empty(2)
# Le max permet de remonter les polarités négatives à 0
features[0] = sum(max(lexicon.get(w, 0), 0) for w in words)/len(words)
features[1] = sum(max(-lexicon.get(w, 0), 0) for w in words)/len(words)
return features
On teste ?
doc = "I came in in the middle of this film so I had no idea about any credits or even its title till I looked it up here, where I see that it has received a mixed reception by your commentators. I'm on the positive side regarding this film but one thing really caught my attention as I watched: the beautiful and sensitive score written in a Coplandesque Americana style. My surprise was great when I discovered the score to have been written by none other than John Williams himself. True he has written sensitive and poignant scores such as Schindler's List but one usually associates his name with such bombasticities as Star Wars. But in my opinion what Williams has written for this movie surpasses anything I've ever heard of his for tenderness, sensitivity and beauty, fully in keeping with the tender and lovely plot of the movie. And another recent score of his, for Catch Me if You Can, shows still more wit and sophistication. As to Stanley and Iris, I like education movies like How Green was my Valley and Konrack, that one with John Voigt and his young African American charges in South Carolina, and Danny deVito's Renaissance Man, etc. They tell a necessary story of intellectual and spiritual awakening, a story which can't be told often enough. This one is an excellent addition to that genre."
doc_features = featurize(doc, lexicon)
doc_features
array([0.12085106, 0.02085106])
Appliquer la fonction précédente sur le mini-corpus IMDB
Commençons par l'extraire
%%bash
cd ../../local
tar -xzf ../data/imdb_smol.tar.gz
ls -lah imdb_smol
total 32K drwxr-xr-x 4 runner docker 4.0K Dec 4 2018 . drwxr-xr-x 4 runner docker 4.0K Nov 14 17:54 .. drwxr-xr-x 2 runner docker 12K Dec 4 2018 neg drwxr-xr-x 2 runner docker 12K Dec 4 2018 pos
tar: Ignoring unknown extended header keyword 'SCHILY.fflags' tar: Ignoring unknown extended header keyword 'SCHILY.fflags' tar: Ignoring unknown extended header keyword 'SCHILY.fflags'
Maintenant on parcourt le dossier pour construire nos représentations
from collections import defaultdict
import pathlib # Manipuler des chemins et des fichiers agréablement
def featurize_dir(corpus_root, lexicon):
corpus_root = pathlib.Path(corpus_root)
res = defaultdict(list)
for clss in corpus_root.iterdir():
# On peut aussi utiliser une compréhension de liste et avoir un dict pas default
for doc in clss.iterdir():
# `stem` et `read_text` c'est de la magie de `pathlib`, check it out
res[clss.stem].append(featurize(doc.read_text(), lexicon))
return res
# On réutilise le lexique précédent
imdb_features = featurize_dir("../../local/imdb_smol", lexicon)
imdb_features
defaultdict(list,
{'neg': [array([0.08676471, 0.08529412]),
array([0.08670213, 0.04946809]),
array([0.08316498, 0.05319865]),
array([0.08421053, 0.09398496]),
array([0.1484127 , 0.00952381]),
array([0.05956284, 0.12622951]),
array([0.06311475, 0.1204918 ]),
array([0.05429363, 0.07174515]),
array([0.05146199, 0.12923977]),
array([0.07116564, 0.08527607]),
array([0.07486631, 0.13315508]),
array([0.02407407, 0.06234568]),
array([0.07 , 0.07916667]),
array([0.05454545, 0.09521531]),
array([0.14132231, 0.09504132]),
array([0.12515593, 0.07900208]),
array([0.07305389, 0.08502994]),
array([0.04791667, 0.06041667]),
array([0.10595745, 0.07234043]),
array([0.04576271, 0.08813559]),
array([0.08531469, 0.04265734]),
array([0.06444444, 0.05703704]),
array([0.12783505, 0.1 ]),
array([0.06893204, 0.13883495]),
array([0.06788321, 0.06788321]),
array([0.10714286, 0.05879121]),
array([0.09303797, 0.04493671]),
array([0.0588993 , 0.10819672]),
array([0.10545455, 0.08484848]),
array([0.06796875, 0.0484375 ]),
array([0.03 , 0.17642857]),
array([0.16165644, 0.09141104]),
array([0.11493506, 0.04967532]),
array([0.08074534, 0.14658385]),
array([0.14615385, 0. ]),
array([0.07666667, 0.06777778]),
array([0.06711712, 0.15630631]),
array([0.09465649, 0.08854962]),
array([0.1392638 , 0.05521472]),
array([0.07928177, 0.09143646]),
array([0.06884735, 0.04548287]),
array([0.21219512, 0.0695122 ]),
array([0.08870968, 0.1 ]),
array([0.08267717, 0.0511811 ]),
array([0.07731959, 0.0371134 ]),
array([0.07626263, 0.07070707]),
array([0.08679245, 0.19622642]),
array([0.03216374, 0.06959064]),
array([0.06142433, 0.09139466]),
array([0.03522727, 0.11818182]),
array([0.0875 , 0.05208333]),
array([0.08109244, 0.09663866]),
array([0.12542373, 0.01101695]),
array([0.04130435, 0.18188406]),
array([0.11463415, 0.02439024]),
array([0.05 , 0.15526316]),
array([0.06412214, 0.06793893]),
array([0.04317181, 0.03612335]),
array([0.12848101, 0.13734177]),
array([0.10334448, 0.10535117]),
array([0.1084507 , 0.16478873]),
array([0.08119658, 0.02606838]),
array([0.07171717, 0.35353535]),
array([0.05925926, 0.09074074]),
array([0.03333333, 0.12345679]),
array([0.07826087, 0.03 ]),
array([0.05375 , 0.110625]),
array([0.15572917, 0.02864583]),
array([0.11086957, 0.05362319]),
array([0.11082803, 0.05286624]),
array([0.10916667, 0.08 ]),
array([0.08092105, 0.07434211]),
array([0.12078652, 0.08370787]),
array([0.06610169, 0.11186441]),
array([0.04756757, 0.08054054]),
array([0.16389776, 0.05015974]),
array([0.03014706, 0.0875 ]),
array([0.08177083, 0.08489583]),
array([0.10855615, 0.0368984 ]),
array([0.0437037 , 0.13037037]),
array([0.05379747, 0.05063291]),
array([0.02387097, 0.08580645]),
array([0.12908587, 0.05900277]),
array([0.09921875, 0.0109375 ]),
array([0.0753915 , 0.11923937]),
array([0.11415929, 0.15132743]),
array([0.12711864, 0.06779661]),
array([0.028125, 0.046875]),
array([0.21219512, 0.0300813 ]),
array([0.066875, 0.086875]),
array([0.065 , 0.01714286]),
array([0.14760563, 0.05211268]),
array([0.048659 , 0.13295019]),
array([0.05768194, 0.07601078]),
array([0.06751825, 0.05930657]),
array([0.14766355, 0.07196262]),
array([0.08796992, 0.07218045]),
array([0.08275862, 0.06767241]),
array([0.16389776, 0.05015974]),
array([0.07927928, 0.01396396]),
array([0.05377834, 0.07619647]),
array([0.06080586, 0.05714286]),
array([0.06733333, 0. ]),
array([0. , 0.15060241]),
array([0.12032967, 0.08571429]),
array([0.1204, 0.0136]),
array([0.0704797 , 0.09372694]),
array([0.11373391, 0.0583691 ]),
array([0.05420168, 0.07647059]),
array([0.08455882, 0.10514706]),
array([0.0992674 , 0.04798535]),
array([0.09 , 0.054]),
array([0.08979592, 0.11088435]),
array([0.14025974, 0.09480519]),
array([0. , 0.06695652]),
array([0.05206612, 0.06446281]),
array([0.09326923, 0.04150641]),
array([0.11755424, 0.02879684]),
array([0.08763441, 0.02204301]),
array([0.04841629, 0.05067873]),
array([0.05597579, 0.08517398]),
array([0.08601399, 0.14545455]),
array([0.16884615, 0.07115385]),
array([0.08058252, 0.04029126]),
array([0.09415205, 0.02690058]),
array([0.08882979, 0.02659574]),
array([0.09637097, 0.08991935]),
array([0.10877193, 0.0754386 ]),
array([0.06048387, 0.05645161]),
array([0.06448911, 0.0881072 ]),
array([0.13939394, 0.13939394]),
array([0.08706468, 0.09303483]),
array([0.07914894, 0.08382979]),
array([0.06493506, 0.10649351]),
array([0.05086705, 0.03583815]),
array([0.11067416, 0.0258427 ]),
array([0.05186441, 0.03966102]),
array([0.10067568, 0.04662162]),
array([0.07264706, 0.07235294]),
array([0.07468354, 0.05759494]),
array([0.07291667, 0.07152778]),
array([0.07289294, 0.05649203]),
array([0.09212121, 0.12484848]),
array([0.08237705, 0.14467213]),
array([0.06340852, 0.07142857]),
array([0.02774194, 0.04129032]),
array([0.23488372, 0.14883721]),
array([0.05985401, 0.08029197]),
array([0.11677852, 0.06040268]),
array([0.09205298, 0.04834437]),
array([0.07728707, 0.11293375]),
array([0.15630631, 0.06306306]),
array([0.04367089, 0.18797468]),
array([0.0467033 , 0.14395604]),
array([0.13225806, 0.06693548]),
array([0.06938776, 0.05918367]),
array([0.0852349 , 0.03825503]),
array([0.10766871, 0.04202454]),
array([0.11703057, 0.04759825]),
array([0.08070175, 0.05112782]),
array([0.05864979, 0.06793249]),
array([0.08527607, 0.06687117]),
array([0.16551724, 0.03448276]),
array([0.11869919, 0.04065041]),
array([0.1847561 , 0.04146341]),
array([0.15795455, 0.07159091]),
array([0.04509804, 0.1 ]),
array([0.02792793, 0.07837838]),
array([0.1 , 0.075]),
array([0.06666667, 0.16769231]),
array([0. , 0.02978723]),
array([0.0377193 , 0.14473684]),
array([0.13613445, 0.07142857]),
array([0.05185185, 0.06157407]),
array([0.0625 , 0.12053571]),
array([0.05238095, 0.03333333]),
array([0.06151203, 0.09965636]),
array([0.08481973, 0.09316888]),
array([0.05391705, 0.12327189]),
array([0.0719697 , 0.07272727]),
array([0.05943396, 0.1 ]),
array([0.08924051, 0.05949367]),
array([0.07687861, 0.07687861]),
array([0.14333333, 0.06333333]),
array([0.08024194, 0.09475806]),
array([0.08445596, 0.12590674]),
array([0.02070175, 0.12736842]),
array([0.04506173, 0.09444444]),
array([0.07878788, 0.13484848]),
array([0.11492537, 0.08955224]),
array([0.025 , 0.12974138]),
array([0.04839858, 0.11281139]),
array([0.03503185, 0.04713376]),
array([0.02402827, 0.04240283]),
array([0.11384615, 0.08307692]),
array([0.0862069 , 0.09655172]),
array([0.07583333, 0.16916667]),
array([0.05095541, 0.02611465]),
array([0.1 , 0.02133333]),
array([0.08878505, 0.0517757 ]),
array([0.10069444, 0.12152778]),
array([0.07103448, 0.11241379]),
array([0.05 , 0.16891892]),
array([0.11400651, 0.05635179]),
array([0.10229008, 0.15877863]),
array([0.05804598, 0.10028736]),
array([0.05873016, 0.05952381]),
array([0.08 , 0.036]),
array([0.11954023, 0.09655172]),
array([0.09190939, 0.08187702]),
array([0.04285714, 0.07278912]),
array([0.08 , 0.1112]),
array([0.04521739, 0.06695652]),
array([0.25203252, 0.01626016]),
array([0.09404762, 0.03333333]),
array([0.05487805, 0.15426829]),
array([0.129, 0.104]),
array([0.0620155 , 0.15426357]),
array([0.15243446, 0.06853933]),
array([0.10352113, 0.02042254]),
array([0.07410072, 0.09100719]),
array([0.08873239, 0.14929577]),
array([0.09134615, 0.07403846]),
array([0.06538462, 0.04505495]),
array([0.05897436, 0.17820513]),
array([0.11639344, 0.05737705]),
array([0.01448276, 0.06413793]),
array([0.09256198, 0.08512397]),
array([0.05751634, 0.04248366]),
array([0.04336283, 0.15132743]),
array([0.0974359 , 0.10512821]),
array([0.14403131, 0.05303327]),
array([0.07248062, 0.15484496]),
array([0.11519435, 0.06007067]),
array([0.06363636, 0.02289562]),
array([0.06941176, 0.03411765]),
array([0.13802281, 0.04081115]),
array([0.07086093, 0.06423841]),
array([0.08129496, 0.04532374]),
array([0.14 , 0.10378378]),
array([0.10422078, 0.0521645 ]),
array([0.14935065, 0.05649351]),
array([0.06535088, 0.20701754]),
array([0.11245421, 0.03113553]),
array([0.13371648, 0.04578544]),
array([0.09769231, 0.05461538]),
array([0.0605042 , 0.21176471]),
array([0.05775862, 0.09568966]),
array([0.11538462, 0.07307692]),
array([0.07509158, 0.14761905]),
array([0.05038168, 0.10763359]),
array([0.033125, 0.081875]),
array([0.06564417, 0.05368098]),
array([0.03333333, 0.1202381 ]),
array([0.09066667, 0.104 ]),
array([0.02130178, 0.13668639]),
array([0.08092486, 0.05144509]),
array([0.09124088, 0.10145985]),
array([0.05423729, 0.10451977]),
array([0.075 , 0.11470588]),
array([0.14324324, 0.11959459]),
array([0.08176101, 0.02044025]),
array([0.10310078, 0.03255814]),
array([0.13630137, 0.07688356]),
array([0.09545455, 0.04090909]),
array([0.0584507, 0.0415493]),
array([0.06896552, 0.03908046]),
array([0.03781513, 0.1802521 ]),
array([0.07361111, 0.05625 ]),
array([0.11230769, 0.02730769]),
array([0.13266332, 0.10753769]),
array([0.0528, 0.1416]),
array([0.04112903, 0.07096774]),
array([0.09626168, 0.03714953]),
array([0.056875, 0.039375]),
array([0.03659849, 0.05489774]),
array([0.07990196, 0.08578431]),
array([0.11818182, 0.0719697 ]),
array([0.06682692, 0.10625 ]),
array([0.09454545, 0.32909091]),
array([0.04769231, 0.09076923]),
array([0.10151515, 0.03151515]),
array([0.05680851, 0.07361702]),
array([0.06234568, 0.02777778]),
array([0.06334107, 0.07030162]),
array([0.09816176, 0.02536765]),
array([0.103125 , 0.0203125]),
array([0.11294118, 0.09529412]),
array([0.07286822, 0.06821705]),
array([0.16075949, 0. ]),
array([0.0546798 , 0.05024631]),
array([0.07276119, 0.05932836]),
array([0.06502947, 0.11591356]),
array([0.03584416, 0.18597403]),
array([0.1260274 , 0.07123288]),
array([0.05699482, 0.09222798]),
array([0.12773723, 0.07153285]),
array([0.08253968, 0.0952381 ]),
array([0.05471698, 0.09119497]),
array([0.12291667, 0.09375 ]),
array([0.08333333, 0.07463768])],
'pos': [array([0.12371795, 0.0275641 ]),
array([0.08244576, 0.11893491]),
array([0.13114754, 0.02540984]),
array([0.07794118, 0.04117647]),
array([0.06015038, 0.12406015]),
array([0.06230769, 0.15 ]),
array([0.07074341, 0.07122302]),
array([0.08363636, 0. ]),
array([0.13536585, 0.07378049]),
array([0.12360248, 0.02608696]),
array([0.14303797, 0.03797468]),
array([0.14480519, 0.03896104]),
array([0.19152542, 0.02711864]),
array([0.07440476, 0.05297619]),
array([0.07868852, 0.0795082 ]),
array([0.05578831, 0.0446527 ]),
array([0.18005698, 0.03447293]),
array([0.14444444, 0.06 ]),
array([0.11072555, 0.05315457]),
array([0.07070313, 0.059375 ]),
array([0.1352518 , 0.03453237]),
array([0.26923077, 0.07948718]),
array([0.13979592, 0.01326531]),
array([0.06631944, 0.07118056]),
array([0.14201183, 0.02840237]),
array([0.09502262, 0.1239819 ]),
array([0.18955224, 0.01641791]),
array([0.18409091, 0.07954545]),
array([0.09040404, 0.03030303]),
array([0.096875, 0. ]),
array([0.09550562, 0.04719101]),
array([0.19492754, 0.04927536]),
array([0.09471154, 0.06923077]),
array([0.23857143, 0.00285714]),
array([0.1883871 , 0.01096774]),
array([0.07637795, 0.07165354]),
array([0.12910663, 0.02334294]),
array([0.11743421, 0.02565789]),
array([0.12515723, 0.00754717]),
array([0.16394558, 0.02040816]),
array([0.07568058, 0.0553539 ]),
array([0.24691358, 0. ]),
array([0.21216216, 0.01283784]),
array([0.28791209, 0.04505495]),
array([0.10882353, 0.00705882]),
array([0.26095238, 0. ]),
array([0.23209877, 0.00679012]),
array([0.16712329, 0.06780822]),
array([0.21481481, 0.01358025]),
array([0.10547112, 0.04042553]),
array([0.14771838, 0.02685789]),
array([0.06806723, 0.00420168]),
array([0.17153846, 0. ]),
array([0.08863636, 0.05170455]),
array([0.08871795, 0.05179487]),
array([0.15025641, 0.0974359 ]),
array([0.10192308, 0.05480769]),
array([0.07575758, 0.02878788]),
array([0.17894737, 0.02894737]),
array([0.071 , 0.1195]),
array([0.14527027, 0.05726351]),
array([0.11232877, 0.00684932]),
array([0.07786885, 0.02213115]),
array([0.1936255 , 0.06135458]),
array([0.09447005, 0.09124424]),
array([0.25777778, 0.07555556]),
array([0.11871658, 0. ]),
array([0.06346154, 0.075 ]),
array([0.07922849, 0.0379822 ]),
array([0.10076923, 0.01615385]),
array([0.10526316, 0.03355263]),
array([0.10900901, 0.02792793]),
array([0.15580448, 0.0287169 ]),
array([0.11013825, 0.05898618]),
array([0.15042017, 0.08319328]),
array([0.21007194, 0.00863309]),
array([0.11265823, 0.05696203]),
array([0.16100629, 0.02830189]),
array([0.19411765, 0. ]),
array([0.15340909, 0.05170455]),
array([0.24299065, 0.09906542]),
array([0.09785203, 0.02673031]),
array([0.17993197, 0.04217687]),
array([0.05594315, 0.03682171]),
array([0.16168582, 0.0651341 ]),
array([0.07474333, 0.06303901]),
array([0.05121951, 0.04731707]),
array([0.09068736, 0.07117517]),
array([0.08285714, 0.05785714]),
array([0.1779661 , 0.02372881]),
array([0.05347594, 0.08235294]),
array([0.18070175, 0.0622807 ]),
array([0.11854305, 0.04635762]),
array([0.07275748, 0.05813953]),
array([0.08812785, 0.08721461]),
array([0.17255639, 0.01616541]),
array([0.1023622, 0.0496063]),
array([0.07931034, 0.06206897]),
array([0.22692308, 0.04 ]),
array([0.22204082, 0.02897959]),
array([0.16586103, 0.03897281]),
array([0.09334862, 0.07591743]),
array([0.06045198, 0.09491525]),
array([0.04705882, 0.06134454]),
array([0.12185792, 0.10874317]),
array([0.1503012 , 0.02409639]),
array([0.14273504, 0.08290598]),
array([0.12054795, 0.01917808]),
array([0.08101266, 0. ]),
array([0.13214286, 0.18214286]),
array([0.12356322, 0.04827586]),
array([0.2625, 0.0775]),
array([0.05532359, 0.14467641]),
array([0.0659292 , 0.02389381]),
array([0.06785714, 0.01919643]),
array([0.08303249, 0.05090253]),
array([0.08783069, 0.05661376]),
array([0.11784777, 0.04356955]),
array([0.06982507, 0.05918367]),
array([0.08187919, 0.0261745 ]),
array([0.11556684, 0.03739425]),
array([0.15727273, 0.02363636]),
array([0.10504732, 0.1170347 ]),
array([0.05200846, 0.02980973]),
array([0.16416667, 0.04083333]),
array([0.09344262, 0.0442623 ]),
array([0.11176471, 0.15294118]),
array([0.11531532, 0.09369369]),
array([0.17794118, 0.09705882]),
array([0.15744681, 0.03723404]),
array([0.07181208, 0.00805369]),
array([0.18075802, 0.10233236]),
array([0.07593985, 0.11879699]),
array([0.25217391, 0. ]),
array([0.0800995 , 0.06716418]),
array([0.14228188, 0.06979866]),
array([0.08963134, 0.10529954]),
array([0.13469388, 0.04387755]),
array([0.1380597 , 0.01119403]),
array([0.10375 , 0.10479167]),
array([0.19302326, 0.04651163]),
array([0.06304348, 0.01884058]),
array([0.03544669, 0.03602305]),
array([0.1075 , 0.05928571]),
array([0.29772727, 0. ]),
array([0.31666667, 0. ]),
array([0.09368421, 0.03578947]),
array([0.0802139 , 0.07058824]),
array([0.17, 0. ]),
array([0.09414634, 0.01853659]),
array([0.24351852, 0.01018519]),
array([0.13382789, 0.09525223]),
array([0.09212598, 0.05984252]),
array([0.21891892, 0.02972973]),
array([0.16160221, 0.03618785]),
array([0.16632997, 0. ]),
array([0.08717949, 0.03931624]),
array([0.07836257, 0.03391813]),
array([0.14845361, 0.03814433]),
array([0.28333333, 0. ]),
array([0.09520384, 0.01846523]),
array([0.13099415, 0.04619883]),
array([0.15793651, 0. ]),
array([0.16907216, 0.02474227]),
array([0.07329193, 0.19192547]),
array([0.12735043, 0.02307692]),
array([0.05963855, 0.06144578]),
array([0.11222222, 0.0062963 ]),
array([0.12857143, 0.02631579]),
array([0.11904762, 0.03285714]),
array([0.0439759 , 0.08162651]),
array([0.07647059, 0.12249135]),
array([0.07741935, 0.07177419]),
array([0.1480315 , 0.02834646]),
array([0.11752577, 0. ]),
array([0.05973597, 0.02112211]),
array([0.05220339, 0.05966102]),
array([0.17019231, 0.05 ]),
array([0.14294479, 0.02699387]),
array([0.19657534, 0.01712329]),
array([0.06440177, 0.05317578]),
array([0.30857143, 0.08285714]),
array([0.12677165, 0.07795276]),
array([0.06514523, 0.08921162]),
array([0.20518519, 0.01777778]),
array([0.09264892, 0.04626109]),
array([0.12105263, 0.01710526]),
array([0.17278912, 0.05578231]),
array([0.19777778, 0.02755556]),
array([0.21741071, 0.06428571]),
array([0.0569378 , 0.06220096]),
array([0.07833333, 0.10916667]),
array([0.08402062, 0.0242268 ]),
array([0.14387755, 0.09985423]),
array([0.12193959, 0.02925278]),
array([0.0671875 , 0.06953125]),
array([0.10923913, 0.07282609]),
array([0.11712707, 0.01160221]),
array([0.06122779, 0.06203554]),
array([0.10520446, 0.07881041]),
array([0.08766234, 0.0512987 ]),
array([0.10753425, 0.0390411 ]),
array([0.08128342, 0.00374332]),
array([0.05776398, 0.07267081]),
array([0.16593407, 0.04871795]),
array([0.08505747, 0.02586207]),
array([0.06923077, 0.00710059]),
array([0.0490566 , 0.06415094]),
array([0.12734375, 0.03164063]),
array([0.05909091, 0.0385101 ]),
array([0.04350649, 0.03636364]),
array([0.09695817, 0.04638783]),
array([0.22876712, 0.10547945]),
array([0.13956522, 0.01695652]),
array([0.09275093, 0.03773234]),
array([0.19055118, 0.01102362]),
array([0.04957983, 0.04453782]),
array([0.125 , 0.01111111]),
array([0.1 , 0.02355769]),
array([0.12085106, 0.02085106]),
array([0.13240741, 0.03518519]),
array([0.08983957, 0.12513369]),
array([0.13282443, 0.00916031]),
array([0.15061728, 0. ]),
array([0.18913043, 0.09492754]),
array([0.12322946, 0.11926346]),
array([0.13333333, 0.01833333]),
array([0.1587156 , 0.03990826]),
array([0.09836957, 0.01630435]),
array([0.11434978, 0.06457399]),
array([0.08557692, 0.0375 ]),
array([0.15467836, 0.02387914]),
array([0.21573034, 0.07977528]),
array([0.07407407, 0. ]),
array([0.11032967, 0.03802198]),
array([0.09246575, 0.09726027]),
array([0.2119403 , 0.08656716]),
array([0.06808511, 0.09219858]),
array([0.3425, 0.0475]),
array([0.21582734, 0.00863309]),
array([0.21083333, 0.03583333]),
array([0.11144578, 0.06144578]),
array([0.0845, 0.055 ]),
array([0.16333333, 0.04388889]),
array([0.10887097, 0.03064516]),
array([0.057277 , 0.06737089]),
array([0.12723005, 0.02253521]),
array([0.13467742, 0. ]),
array([0.2462963, 0. ]),
array([0.11921922, 0.10930931]),
array([0.12985075, 0.01455224]),
array([0.16530612, 0.05020408]),
array([0.07941176, 0.02352941]),
array([0.08321429, 0.09178571]),
array([0.0908377 , 0.02041885]),
array([0.06206262, 0.15138122]),
array([0.12521008, 0.03193277]),
array([0.12947368, 0.03684211]),
array([0.14375 , 0.13303571]),
array([0.1968254 , 0.12063492]),
array([0.19439252, 0.0411215 ]),
array([0.03308271, 0.08220551]),
array([0.15747126, 0.01896552]),
array([0.08019802, 0. ]),
array([0.14796748, 0.07723577]),
array([0.09496855, 0.07374214]),
array([0.08368794, 0.05035461]),
array([0.17478992, 0. ]),
array([0.10551724, 0.03862069]),
array([0.0542654 , 0.10829384]),
array([0.19510204, 0.0322449 ]),
array([0.14545455, 0.12626263]),
array([0.15185185, 0.13111111]),
array([0.2283871, 0. ]),
array([0.25590551, 0. ]),
array([0.11642857, 0. ]),
array([0.11325758, 0.01799242]),
array([0.18455882, 0. ]),
array([0.19230769, 0.05664336]),
array([0.14641148, 0.03301435]),
array([0.1052459 , 0.09409836]),
array([0.14467213, 0.03770492]),
array([0.09568627, 0.08058824]),
array([0.13609467, 0.0260355 ]),
array([0.11803279, 0.03442623]),
array([0.15692308, 0.05230769]),
array([0.03370787, 0.04269663]),
array([0.10625 , 0.01420455]),
array([0.14125, 0.04 ]),
array([0.11280788, 0.0320197 ]),
array([0.09032258, 0.05096774]),
array([0.11912046, 0.11414914]),
array([0.07537688, 0.0440536 ]),
array([0.04651163, 0.0627907 ]),
array([0.09518717, 0.0802139 ]),
array([0.06254296, 0.03883162]),
array([0.18062016, 0.08449612]),
array([0.12865014, 0.0661157 ]),
array([0.17945205, 0.01438356]),
array([0.2630137 , 0.06575342]),
array([0.025 , 0.02785714])]})
Comment se répartissent les documents du corpus avec la représentation qu'on a choisi
import matplotlib.pyplot as plt
import seaborn as sns
X = np.array([d[0] for d in (*imdb_features["pos"], *imdb_features["neg"])])
Y = np.array([d[1] for d in (*imdb_features["pos"], *imdb_features["neg"])])
H = np.array([*("pos" for _ in imdb_features["pos"]), *("neg" for _ in imdb_features["neg"])])
fig = plt.figure(dpi=200)
sns.scatterplot(x=X, y=Y, hue=H, s=5)
plt.show()
On voit des tendances qui se dégagent, mais clairement ça va être un peu coton
On considère des vecteurs de features de dimension $n$
$$\mathbf{x} = (x₁, …, x_n)$$Un vecteur de poids de dimension $n$
$$\mathbf{w} = (w₁, …, w_n)$$et un biais $b$ scalaire (un nombre quoi).
Pour réaliser une classification on considère le nombre $z$ (on parle parfois de logit)
$$z=w₁×x₁ + … + w_n×x_n + b = \sum_iw_ix_i + b$$Ce qu'on note aussi
$$z = \mathbf{w}⋅\mathbf{x}+b$$$\mathbf{w}⋅\mathbf{x}$ se lit « w scalaire x », on parle de produit scalaire en français et de inner product en anglais.
(ou pour les mathématicien⋅ne⋅s acharné⋅e⋅s $z = \langle w\ |\ x \rangle + b$)
Quelle que soit la façon dont on le note, on affectera à $\mathbf{x}$ la classe $0$ si $z < 0$ et la classe $1$ sinon.
Écrire une fonction qui prend en entrée un vecteur de features et un vecteur de poids sous forme de
tableaux numpy $x$ et $w$ de dimensions (n,) et un biais $b$ sous forme d'un tableau numpy de
dimensions (1,) et renvoie $z=\sum_iw_ix_i + b$.
def affine_combination(x, w, b):
pass # À vous de jouer !
affine_combination(
np.array([2, 0, 2, 1]),
np.array([-0.2, 999.1, 0.5, 2]),
np.array([1]),
)
Une version élémentaire avec des boucles
def affine_combination(x, w, b):
res = np.zeros(1)
for wi, xi in zip(w, x):
res += wi*xi
res += b
return res
affine_combination(
np.array([2, 0, 2, 1]),
np.array([-0.2, 999.1, 0.5, 2]),
np.array([1]),
)
array([3.6])
Une version plus courte avec les fonctions natives de numpy
def affine_combination(x, w, b):
return np.inner(w, x) + b
affine_combination(
np.array([2, 0, 2, 1]),
np.array([-0.2, 999.1, 0.5, 2]),
np.array([1]),
)
array([3.6])
Écrire un classifieur linéaire qui prend en entrée des vecteurs de features à deux dimensions précédents et utilise les poids respectifs $0.6$ et $-0.4$ et un biais de $-0.01$. Appliquez ce classifieur sur le mini-corpus IMDB qu'on a vectorisé et calculez son exactitude.
def hardcoded_classifier(x):
return False # À vous de jouer
hardcoded_classifier(doc_features)
False
On commence par définir le classifieur : on va renvoyer True pour la classe positive et False
pour la classe négative.
def hardcoded_classifier(x):
return affine_combination(x, np.array([0.6, -0.4]), -0.01) > 0.0
hardcoded_classifier(doc_features)
True
Maintenant on le teste
correct_pos = sum(1 for doc in imdb_features["pos"] if hardcoded_classifier(doc))
print(f"Recall for 'pos': {correct_pos}/{len(imdb_features['pos'])}={correct_pos/len(imdb_features['pos']):.02%}")
correct_neg = sum(1 for doc in imdb_features["neg"] if not hardcoded_classifier(doc))
print(f"Recall for 'neg': {correct_neg}/{len(imdb_features['neg'])}={correct_neg/len(imdb_features['neg']):.02%}")
print(f"Accuracy: {correct_pos+correct_neg}/{len(imdb_features['pos'])+len(imdb_features['neg'])}={(correct_pos+correct_neg)/(len(imdb_features['pos'])+len(imdb_features['neg'])):.02%}")
Recall for 'pos': 269/301=89.37% Recall for 'neg': 118/301=39.20% Accuracy: 387/602=64.29%
On en fait une fonction, ça nous sera utile plus tard
def classifier_accuracy(w, b, featurized_corpus):
correct_pos = sum(1 for doc in imdb_features["pos"] if affine_combination(doc, w, b) > 0.0)
correct_neg = sum(1 for doc in imdb_features["neg"] if affine_combination(doc, w, b) <= 0.0)
return (correct_pos+correct_neg)/(len(featurized_corpus['pos'])+len(featurized_corpus['neg']))
classifier_accuracy(np.array([0.6, -0.4]), np.array(-0.01), imdb_features)
0.6428571428571429
Pourquoi linéaire ? Regardez la figure suivante qui colore les points $(x,y)$ du plan en fonction de la valeur de $z$.
import tol_colors as tc
x = np.linspace(0, 1, 1000)
y = np.linspace(0, 1, 1000)
X, Y = np.meshgrid(x, y)
Z = (0.6*X - 0.4*Y) - 0.01
fig = plt.figure(dpi=200)
heatmap = plt.pcolormesh(X, Y, Z, shading="auto", cmap=tc.tol_cmap("sunset"))
plt.colorbar(heatmap)
plt.show()
Ou encore plus clairement, si on représente la classe assignée
import tol_colors as tc
x = np.linspace(0, 1, 1000)
y = np.linspace(0, 1, 1000)
X, Y = np.meshgrid(x, y)
Z = (0.6*X - 0.4*Y) -0.01 > 0.0
fig = plt.figure(dpi=200)
heatmap = plt.pcolormesh(X, Y, Z, shading="auto", cmap=tc.tol_cmap("sunset"))
plt.colorbar(heatmap)
plt.show()
On voit bien que la frontière de classification est une droite, a line. On a donc un linear classifier : un classifieur linéaire (même si en français on dirait qu'il s'agit d'une fonction affine).
Qu'est-ce que ça donne si on superpose avec notre corpus ?
fig = plt.figure(dpi=200)
x = np.linspace(0, 0.4, 1000)
y = np.linspace(0, 0.4, 1000)
X, Y = np.meshgrid(x, y)
Z = (0.6*X - 0.4*Y) -0.01 > 0.0
heatmap = plt.pcolormesh(X, Y, Z, shading="auto", cmap=tc.tol_cmap("sunset"))
X = np.array([d[0] for d in (*imdb_features["pos"], *imdb_features["neg"])])
Y = np.array([d[1] for d in (*imdb_features["pos"], *imdb_features["neg"])])
H = np.array([*(1 for _ in imdb_features["pos"]), *(0 for _ in imdb_features["neg"])])
plt.scatter(x=X, y=Y, c=H, cmap="viridis", s=5)
plt.show()
Pas si surprenant que nos résultats ne soient pas terribles…
Elle permet de normaliser $z$ : $z$ peut être n'importe quel nombre entre $-∞$ et $+∞$, mais on aura toujours $0 < σ(z) < 1$, ce qui permet de l'interpréter facilement comme une vraisemblance. Autrement dit, $σ(z)$ sera proche de $1$ s'il paraît vraisemblable que $x$ appartienne à la classe $1$ et proche de $0$ sinon.
Tracer avec matplotlib la courbe représentative de la fonction logistique.
def logistic(z):
return 1/(1+np.exp(-z))
%matplotlib inline
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 5000)
y = logistic(x)
plt.plot(x, y)
plt.xlabel("$x$")
plt.ylabel("$σ(x)$")
plt.title("Courbe représentative de la fonction logistique sur $[-10, 10]$")
plt.show()
Formellement : on suppose qu'il existe une fonction $f$ qui prédit parfaitement les classes, donc telle que pour tout couple exemple/étiquette $(x, y)$ avec $y$ valant $0$ ou $1$, $f(x) = y$. On approcher cette fonction par une fonction $g$ de la forme
$$g(x) = σ(w⋅x+b)$$Si on choisit les poids $w$ et le biais $b$ tels que $g$ soit la plus proche possible de $f$ sur notre ensemble d'apprentissage, on dit que $g$ est la régression logistique de $f$ sur cet ensemble.
Un classifieur logistique, c'est simplement un classifieur qui pour un exemple $x$ renvoie $0$ si $g(x) < 0.5$ et $1$ sinon. Il a exactement les mêmes capacités de discrimination qu'un classifieur linéaire (sa frontière de décision est la même et il ne sait donc pas prendre de décisions plus complexes), mais on peut interpréter la confiance qu'il a dans sa décision.
Par exemple voici la confiance que notre classifieur codé en dur a en ses décisions
def classifier_confidence(x):
return logistic(affine_combination(x, np.array([0.6, -0.4]), -0.01))
g_x = classifier_confidence(doc_features)
display(g_x)
display(Markdown(f"Le classifieur est sûr à {g_x:.06%} que ce document est dans la classe $1$."))
display(Markdown(f"Autrement dit, d'après le classifieur, la classe $1$ a {g_x:.06%} de vraisemblance pour ce document"))
0.5135392425438052
Le classifieur est sûr à 51.353924% que ce document est dans la classe $1$.
Autrement dit, d'après le classifieur, la classe $1$ a 51.353924% de vraisemblance pour ce document
Quelle est la vraisemblance de la classe $0$ (review négative) ? Et bien le reste
1.0 - classifier_confidence(doc_features)
0.48646075745619477
Comme l'exemple en question appartient bien à cette classe, ça signifie que notre classifieur et plutôt bon sur cet exemple. L'est-il sur le reste du corpus ?
pos_confidence = sum(classifier_confidence(doc) for doc in imdb_features["pos"])
print(f"Average confidence for 'pos': {pos_confidence/len(imdb_features['pos']):.02%}")
neg_confidence = sum(1-classifier_confidence(doc) for doc in imdb_features["neg"])
print(f"Average confidence for 'neg': {neg_confidence/len(imdb_features['neg']):.02%}")
print(f"Average confidence for the correct class: {(pos_confidence+neg_confidence)/(len(imdb_features['pos']) + len(imdb_features['neg'])):.02%}")
Average confidence for 'pos': 51.18% Average confidence for 'neg': 49.80% Average confidence for the correct class: 50.49%
Autrement dit, pour un exemple pris au hasard dans le corpus, la vraisemblance de sa classe telle que jugée par le classifieur sera de $50.49\%$. Un classifieur parfait obtiendrait $100\%$, un classifieur qui prendrait systématiquement la mauvaise décision $0\%$ et un classifieur aléatoire uniforme $50\%$ (puisque notre corpus a autant d'exemples de chaque classe).
Moralité : nos poids ne sont pas très bien choisis, et notre préoccupation dans la suite va être de chercher comment choisir des poids pour que la confiance moyenne de la classe correcte soit aussi haute que possible.
On a dit que notre objectif était
Chercher les poids $w$ et le biais $b$ tels que $g$ soit la plus proche possible de $f$ sur notre ensemble d'apprentissage
On formalise « être le plus proche possible » de la section précédente comme minimiser une certaine fonction de coût (loss) $L$ qui mesure l'erreur faite par le classifieur sur un exemple.
$$L(g(x), y) = \text{l'écart entre la classe prédite par $g$ pour $x$ et la classe correcte $y$}$$Étant donné un ensemble de test $(x₁, y₁), …, (x_n, y_n)$, on estime l'erreur faite par le classifieur logistique $g$ pour chaque exemple $(x_i, y_i)$ comme le coût local $L(g(xᵢ), yᵢ)$ et son erreur sur tout l'ensemble de test par le coût global $\mathcal{L}$ :
$$\mathcal{L} = \sum_i L(g(xᵢ), yᵢ)$$Plus $\mathcal{L}$ sera bas, meilleur sera notre classifieur.
Dans le cas de la régression logistique, on va s'inspirer de ce qu'on a vu dans la section précédente et utiliser la log-vraisemblance négative (negative log-likelihood) :
On définit la vraisemblance $V$ comme précédemment par $$ V(a, y) = \begin{cases} a & \text{si $y = 1$}\\ 1-a & \text{sinon} \end{cases} $$
Intuitivement, il s'agit de la vraisemblance affectée par le modèle à la classe correcte $y$. Il ne s'agit donc pas d'un coût, mais d'un gain (si sa valeur est haute, c'est que le modèle est bon)
La log-vraisemblance négative $L$ est alors définie par
$$L(a, y) = -\log(V(a, y))$$Le $\log$ est là pour plusieurs raisons, calculatoires et théoriques1 et le $-$ à s'assurer qu'on a bien un coût (plus la valeur est basse, meilleur le modèle est).
1. Entre autres, comme pour *Naïve Bayes*, parce qu'une somme de $\log$-vraisemblance peut être vue comme le $\log$ de la probabilité d'une conjonction d'événements indépendants. Mais surtout parce qu'il rend la fonction de coût **convexe** par rapport à $w$.
Une interprétation possible : $L(a, y)$, c'est la surprise de $y$ au sens de la théorie de l'information. Autrement dit : si j'estime qu'il y a une probabilité $a$ d'observer la classe $y$, $L(a, y)$ mesure à quel point il serait surprenant d'observer effectivement $y$.
On peut vérifier qu'il s'agit bien d'un coût :
Si le classifieur prend une décision correcte avec une confiance parfaite le coût est nul :
$$ \begin{cases}
L(1.0, 1) = -\log(1.0) = 0\\
L(0.0, 0) = -\log(1.0-0.0) = -\log(1.0) = 0
\end{cases} $$
Si le classifieur prend une décision erronée avec une confiance parfaite le coût est infini :
$$ \begin{cases}
L(0.0, 1) = -\log(0.0) = +\infty\\
L(1.0, 0) = -\log(1.0-1.0) = \log(0.0) = +\infty
\end{cases} $$
On peut aussi vérifier facilement que $L(a, 1)$ est décroissant par rapport à $a$ et que $L(1-a, 0)$ est croissant par rapport à $a$. Autrement dit, plus le classifieur juge que la classe correcte est vraisemblable plus le coût $L$ est bas.
Enfin, on peut l'écrire $L$ en une ligne : pour un exemple $x$, le coût de l'exemple $(x, y)$ est
$$L(g(x), y) = -\log\left[g(x)×y + (1-g(x))×(1-y)\right]$$C'est un trick, l'astuce c'est que comme $y$ vaut soit $0$ soit $1$, soit $y=0$, soit $1-y=0$ et donc la somme dans le $\log$ se simplifie dans tous les cas. Rien de transcendant là-dedans.
La formule diffère un peu de celle de Speech and Language Processing, mais les résultats sont les mêmes et celle-ci est mieux pour notre problème !
En fait la leur est la formule générale de l'entropie croisée pour des distributions de proba à support dans $\{0, 1\}$, ce qui est une autre intuition pour cette fonction de coût, mais ici elle nous complique la vie.
Une dernière façon de l'écrire en une ligne :
$$L(g(x), y) = -\log\left[g(x)\mathbb{1}_{y=1} + (1-g(x))\mathbb{1}_{y=0}\right]$$Écrire une fonction qui prend en entrée
Et renvoie la log-vraisemblance négative du classifieur logistique de poids $(w, b)$ pour l'exemple $(x, y)$.
Servez-vous en pour calculer le coût du classifieur de l'exercise précédent sur le mini-corpus IMDB.
def logistic_negative_log_likelihood(x, w, b, y):
g_x = logistic(affine_combination(x, w, b))
if y == 1:
correct_likelihood = g_x
else:
correct_likelihood = 1-g_x
loss = -np.log(correct_likelihood)
return loss
def loss_on_imdb(w, b, featurized_corpus):
loss_on_pos = np.zeros(1)
for doc_features in featurized_corpus["pos"]:
loss_on_pos += logistic_negative_log_likelihood(
doc_features, w, b, 1
)
loss_on_neg = np.zeros(1)
for doc_features in featurized_corpus["neg"]:
loss_on_neg += logistic_negative_log_likelihood(
doc_features, w, b, 0
)
return loss_on_pos + loss_on_neg
Avec des compréhensions
def loss_on_imdb(w, b, featurized_corpus):
loss_on_pos = sum(
logistic_negative_log_likelihood(doc_features, w, b, 1)
for doc_features in featurized_corpus["pos"]
)
loss_on_neg = sum(
logistic_negative_log_likelihood(doc_features, w, b, 0)
for doc_features in featurized_corpus["neg"]
)
return loss_on_pos + loss_on_neg
En version numériquement stable
import math
def loss_on_imdb(w, b, featurized_corpus):
loss_on_pos = math.fsum(
logistic_negative_log_likelihood(doc_features, w, b, 1).astype(float)
for doc_features in featurized_corpus["pos"]
)
loss_on_neg = math.fsum(
logistic_negative_log_likelihood(doc_features, w, b, 0).astype(float)
for doc_features in featurized_corpus["neg"]
)
return np.array([loss_on_pos + loss_on_neg])
loss_on_imdb(np.array([0.6, -0.4]), -0.01, imdb_features)
array([411.54449928])
L'algorithme de descente de gradient est la clé de voute de l'essentiel des travaux en apprentissage artificiel moderne. Il s'agit d'un algorithme itératif qui étant donné un modèle paramétrisé et une fonction de coût (avec des hypothèses de régularité assez faibles) permet de trouver des valeurs des paramètres pour lesquelles la fonction de coût est minimal.
On ne va pas rentrer dans les détails de l'algorithme de descente de gradient stochastique, mais juste essayer de se donner quelques idées.
L'intuition à avoir est la suivante : si vous êtes dans une vallée et que vous voulez trouver rapidement le point le plus bas, une façon de faire est de chercher la direction vers laquelle la pente descend le plus vite, de faire quelques pas dans cette direction puis de recommencer. On parle aussi pour cette raison d'algorithme de la plus forte pente.
Clairement une condition pour que ça marche peu importe le point de départ, c'est que la vallée n'ait qu'un seul point localement le plus bas. Par exemple ça marche avec une vallée comme celle-ci
%matplotlib inline
import tol_colors as tc
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(20, 20), dpi=200)
ax = plt.axes(projection='3d')
r = np.linspace(0, 8, 100)
p = np.linspace(0, 2*np.pi, 100)
R, P = np.meshgrid(r, p)
Z = R**2 - 1
X, Y = R*np.cos(P), R*np.sin(P)
ax.plot_surface(X, Y, Z, cmap=tc.tol_cmap("sunset"), edgecolor="none", rstride=1, cstride=1)
ax.plot_wireframe(X, Y, Z, color='black')
plt.show()
Mais pas pour celle-là
%matplotlib inline
import tol_colors as tc
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(20, 20), dpi=200)
ax = plt.axes(projection='3d')
r = np.linspace(0, 8, 100)
p = np.linspace(0, 2*np.pi, 100)
R, P = np.meshgrid(r, p)
Z = -np.cos(R)/(1+0.5*R**2)
X, Y = R*np.cos(P), R*np.sin(P)
ax.plot_surface(X, Y, Z, cmap=tc.tol_cmap("sunset"), edgecolor="none", rstride=1, cstride=1)
#ax.plot_wireframe(X, Y, Z, color='black')
plt.show()
OK, mais comment on trouve la plus forte pente en pratique ? En une dimension il suffit de suivre l'opposé du nombre dérivé : https://uclaacm.github.io/gradient-descent-visualiser/#playground
En plus de dimensions, c'est plus compliqué, mais on peut s'en sortir en suivant le gradient qui est une généralisation du nombre dérivé : https://jackmckew.dev/3d-gradient-descent-in-python.html
Ce qui fait marcher la machine c'est que le gradient indique la direction dans laquelle la fonction croît le plus vite. Et que l'opposé du gradient indique la direction dans laquelle la fonction décroît le plus vite.
(localement)
Concrètement si on veut trouver $\theta$ tel que $f(\theta)$ soit minimale pour une certaine
fonction $f$ dont le gradient est donné par grad_f ça donne l'algo suivant
def descent(grad_f, theta_0, learning_rate, n_steps):
theta = theta_0
for _ in range(n_steps):
# On trouve la direction de plus grande pente
steepest_direction = -grad_f(theta)
# On fait quelques pas dans cette direction
theta += learning_rate*steepest_direction
return theta
Les hyperparamètres sont
theta_0 est notre point de départ, notre première estimation d'où se trouvera le minimum, que
l'algorithme va raffiner. Évidemment si on a déjà une idée de vers où on pourrait le trouver, ça
ira plus vite. Si on a aucune idée, on peut le prendre aléatoire.learning_rate ou « taux d'apprentissage » : de combien on se déplace à chaque étape. Si on le
prend grand on arrive vite vers la région du minimum, on mettra longtemps pour en trouver une
approximation précise. Si on le prend petit, ça sera l'inverse.n_steps est le nombre d'étapes d'optimisations. Dans un problème d'apprentissage, c'est aussi le
nombre de fois où on aura parcouru l'ensemble d'apprentissage et on parle souvent d'epochIci on se donne un nombre fixe d'epochs, une autre possibilité serait de s'arrêter quand on ne bouge plus trop, par exemple avec une condition comme
if np.max(grad_f(theta)) < 0.00001:
break
dans la boucle et éventuellement avec une boucle infinie while True.
Point notation :
Rappelez-vous, on a dit que notre fonction de coût, c'était
$$\mathcal{L} = \sum_i L(g(xᵢ), yᵢ)$$et on cherche la valeur du paramètre $θ = (w_1, …, w_n, b)$ tel que $\mathcal{L}$ soit le plus petit possible.
On peut utilise la propriété d'additivité du gradient : pour deux fonctions $f$ et $g$, on a
$$\operatorname{grad}(f+g) = \operatorname{grad}f + \operatorname{grad}g$$Donc ici
$$\operatorname{grad}\mathcal{L} = \sum_i \operatorname{grad}L(g(xᵢ), yᵢ)$$Si on dispose d'une fonction grad_L qui, étant donnés $g(x_i)$ et $y_i$, renvoie
$\operatorname{grad}L(g(x_i), y_i)$, l'algorithme de descente du gradient devient alors
def descent(train_set, theta_0, learning_rate, n_steps):
theta = theta_0
for _ in range(n_steps):
w = theta[:-1]
b = theta[-1]
partial_grads = []
for (x, y) in train_set:
# On calcule g(x)
g_x = logistic(np.inner(w,x)+b)
# On calcule le gradient de L(g(x), y))
partial_grads.append(grad_L(g_x, y))
# On trouve la direction de plus grande pente
steepest_direction = -np.sum(partial_grads)
# On fait quelques pas dans cette direction
theta += learning_rate*steepest_direction
return theta
Pour chaque étape, on doit calculer tous les $g(x_i)$ et $\operatorname{grad}L(g(x_i), y_i)$. C'est très couteux, il doit y avoir moyen de faire mieux.
Si les $L(g(xᵢ), yᵢ)$ étaient indépendants, ce serait plus simple : on pourrait les optimiser séparément.
Ce n'est évidemment pas le cas : si on change $g$ pour que $g(x_0)$ soit plus proche de $y_0$, ça changera aussi la valeur de $g(x_1)$.
Mais on va faire comme si
C'est une approximation sauvage, mais après tout on commence à avoir l'habitude. On va donc suivre l'algo suivant
def descent(train_set, theta_0, learning_rate, n_steps):
theta = theta_0
for _ in range(n_steps):
for (x, y) in train_set:
w = theta[:-1]
b = theta[-1]
# On calcule g(x)
g_x = logistic(np.inner(w,x)+b)
# On trouve la direction de plus grande pente
steepest_direction = -grad_L(g_x, y)
# On fait quelques pas dans cette direction
theta += learning_rate*steepest_direction
return theta
Faites bien attention à la différence : au lieu d'attendre d'avoir calculé tous les $\operatorname{grad}L(g(x_i), y_i)$ avant de modifier $θ$, on va le modifier à chaque fois.
Notre espoir ici c'est que cette situation n'arrivera pas, et qu'on bon paramètre pour un certain
couple $(x, y)$ c'est un bon paramètres pour $tous$ les couples (exemple, classe).
Ce nouvel algorithme s'appelle l'algorithme de descente de gradient stochastique, et il est crucial pour nous, parce qu'on ne pourra en pratique quasiment jamais faire de descente de gradient globale.
Il ne nous reste plus qu'à savoir comment on calcule grad_L. On ne fera pas la preuve, mais on a
et
Autrement dit on mettra à jour $w$ en calculant
$$w ← w -η×\operatorname{d}_wL(g(x), y) = w - η×(g(x)-y)x$$$\operatorname{d}_wL(g(x), y) = \left(\frac{∂L(g(x), y)}{∂w_1}, …, \frac{∂L(g(x), y)}{∂w_n}\right)$ est la *différentielle partielle* de $L(g(x), y)$ par rapport à $w$.
Et $b$ en calculant
$$b ← b -η×\frac{∂L(g(x), y)}{∂b} = b - η×(g(x)-y)$$def grad_L(x, w, b, y):
grad = np.zeros(w.size+b.size) # À vous !
return grad
grad_L(np.array([5, 10]), np.array([0.6, -0.4]), np.array([-0.01]), 0)
array([0., 0., 0.])
def grad_L(x, w, b, y):
g_x = logistic(np.inner(w, x) + b)
grad_w = (g_x - y)*x
grad_b = g_x - y
return np.append(grad_w, grad_b)
grad_L(np.array([5, 10]), np.array([0.6, -0.4]), np.array([-0.01]), 0)
array([1.33489925, 2.66979851, 0.26697985])
S'en servir pour apprendre les poids à donner aux features précédentes à l'aide du mini-corpus IMDB en utilisant l'algorithme de descente de gradient stochastique.
def descent(featurized_corpus, theta_0, learning_rate, n_steps):
theta = theta_0
for _ in range(n_steps):
pass # À vous !
return
descent(imdb_features, np.array([0.6, -0.4, 0.0]), 0.001, 100)
Version minimale
import random
def descent(featurized_corpus, theta_0, learning_rate, n_steps):
train_set = [
*((doc, 1) for doc in featurized_corpus["pos"]),
*((doc, 0) for doc in featurized_corpus["neg"])
]
theta = theta_0
w = theta[:-1]
b = theta[-1]
for i in range(n_steps):
# On mélange le corpus pour s'assurer de ne pas avoir d'abord tous
# les positifs puis tous les négatifs
random.shuffle(train_set)
for j, (x, y) in enumerate(train_set):
grad = grad_L(x, w, b, y)
steepest_direction = -grad
theta += learning_rate*steepest_direction
w = theta[:-1]
b = theta[-1]
return (theta[:-1], theta[-1])
Avec du feedback pour voir ce qui se passe
def descent_with_logging(featurized_corpus, theta_0, learning_rate, n_steps):
train_set = [
*((doc, 1) for doc in featurized_corpus["pos"]),
*((doc, 0) for doc in featurized_corpus["neg"])
]
theta = theta_0
theta_history = [theta_0.tolist()]
w = theta[:-1]
b = theta[-1]
print("Epoch\tLoss\tAccuracy\tw\tb")
print(f"Initial\t{loss_on_imdb(w, b, featurized_corpus).item()}\t{classifier_accuracy(w, b, featurized_corpus)}\t{w}\t{b}")
for i in range(n_steps):
# On mélange le corpus pour s'assurer de ne pas avoir d'abord tous
# les positifs puis tous les négatifs
random.shuffle(train_set)
for j, (x, y) in enumerate(train_set):
grad = grad_L(x, w, b, y)
steepest_direction = -grad
# Purement pour l'affichage
loss = logistic_negative_log_likelihood(x, w, b, y)
#print(f"step {i*len(train_set)+j} doc={x}\tw={w}\tb={b}\tloss={loss}\tgrad={grad}")
theta += learning_rate*steepest_direction
w = theta[:-1]
b = theta[-1]
theta_history.append(theta.tolist())
epoch_train_loss = loss_on_imdb(w, b, featurized_corpus).item()
epoch_train_accuracy = classifier_accuracy(w, b, imdb_features)
print(f"{i}\t{epoch_train_loss}\t{epoch_train_accuracy}\t{w}\t{b}")
return (theta[:-1], theta[-1]), theta_history
theta, theta_history = descent_with_logging(imdb_features, np.array([0.6, -0.4, -0.01]), 0.1, 100)
Epoch Loss Accuracy w b Initial 411.5444992792534 0.6428571428571429 [ 0.6 -0.4] -0.01 0 406.93408906203297 0.5664451827242525 [ 1.19686632 -0.87932925] -0.20234147737977798 1 400.6352559721495 0.686046511627907 [ 1.78694288 -1.32281787] -0.17679599216481598 2 397.41829882885463 0.6245847176079734 [ 2.33075208 -1.73988067] -0.2955867147830101 3 391.11768383596325 0.6910299003322259 [ 2.87195981 -2.12342543] -0.18349588640222017 4 388.79119862637555 0.6495016611295681 [ 3.37879167 -2.50000499] -0.04589058469949964 5 383.4798413636877 0.6943521594684385 [ 3.84555264 -2.88843559] -0.22796769534332667 6 384.81675286653274 0.6511627906976745 [ 4.26859675 -3.26086056] -0.49018373679045446 7 378.7706825181755 0.6827242524916943 [ 4.70899657 -3.60493077] -0.4118334495728779 8 377.8677028538098 0.6843853820598007 [ 5.10832448 -3.94024625] -0.5015061987209349 9 372.6342525050655 0.6810631229235881 [ 5.52864279 -4.23715304] -0.20880650955973715 10 369.88911840738444 0.6794019933554817 [ 5.89822217 -4.53704583] -0.2676465436354125 11 368.9603280869377 0.6993355481727574 [ 6.23129653 -4.83846102] -0.4847283657318344 12 367.9285377556978 0.6910299003322259 [ 6.5681939 -5.12650623] -0.5419181769219807 13 367.0625010047238 0.6843853820598007 [ 6.89001608 -5.40084085] -0.5911689144941211 14 365.2819907309063 0.6910299003322259 [ 7.19912486 -5.66861407] -0.6025874347123347 15 361.5234874081543 0.6943521594684385 [ 7.50318338 -5.92287353] -0.5211593178488833 16 362.1089579165464 0.6976744186046512 [ 7.78648947 -6.16942472] -0.6248042656620694 17 358.5553172516203 0.6810631229235881 [ 8.09678496 -6.38167194] -0.3402005285666376 18 357.5504669103534 0.6843853820598007 [ 8.3421799 -6.61940726] -0.5618319523726477 19 357.08629590590414 0.6794019933554817 [ 8.62957881 -6.81825831] -0.31651693516886276 20 355.11721269399226 0.6877076411960132 [ 8.85189508 -7.04921657] -0.5701768501279735 21 354.91552270940673 0.6794019933554817 [ 9.10365838 -7.23231514] -0.3474718670058891 22 354.77519525023695 0.6810631229235881 [ 9.33429963 -7.42445316] -0.32387241944441514 23 354.76040097613 0.7009966777408638 [ 9.51385428 -7.64254902] -0.7133938488723173 24 357.20354445515113 0.6893687707641196 [ 9.71061446 -7.83822179] -0.8152515833641201 25 350.99774871023703 0.6827242524916943 [ 9.95671327 -7.99845637] -0.42459627819353574 26 353.3720130546455 0.6877076411960132 [10.16947408 -8.1678022 ] -0.3012007356071095 27 352.2117866379821 0.6827242524916943 [10.35006099 -8.33430587] -0.3263488863456583 28 348.3569344643432 0.6943521594684385 [10.50897522 -8.52156426] -0.5423831210674112 29 347.88982402066574 0.6926910299003323 [10.6847333 -8.68190409] -0.5205876987522734 30 351.0388807985513 0.7043189368770764 [10.82996407 -8.85619788] -0.8021376545837785 31 347.71154909279596 0.6910299003322259 [11.00753919 -8.99842764] -0.6920013427803972 32 346.4421098793488 0.6976744186046512 [11.17175606 -9.15621426] -0.6288068554975508 33 347.62766308523373 0.6794019933554817 [11.35105074 -9.28372227] -0.42378443649096226 34 345.72704357828053 0.6926910299003323 [11.47943504 -9.44271603] -0.6611678880621426 35 345.71959432313986 0.6943521594684385 [11.626494 -9.58666516] -0.7022995090486093 36 345.57849610046173 0.6827242524916943 [11.79106426 -9.70796174] -0.4868748459723051 37 354.908909746996 0.6727574750830565 [11.96177409 -9.82284732] -0.21148739973832814 38 344.4603986829358 0.6926910299003323 [12.04417566 -9.98316972] -0.7041375321357304 39 359.03600566812065 0.659468438538206 [ 12.22575758 -10.06800246] -0.13869947292654597 40 344.40935165103406 0.6843853820598007 [ 12.31275257 -10.21832794] -0.4999294759865236 41 343.1333548222175 0.6910299003322259 [ 12.42791898 -10.34105672] -0.602416578236249 42 342.8282912446356 0.6926910299003323 [ 12.53532236 -10.45748149] -0.6290500646504267 43 346.96552518597866 0.686046511627907 [ 12.67503293 -10.55501191] -0.381089878998483 44 348.68044133096504 0.6843853820598007 [ 12.79154342 -10.66482018] -0.33247660729720985 45 342.89239996387863 0.6810631229235881 [ 12.87560849 -10.78384202] -0.5394335145154703 46 345.29516860473757 0.6777408637873754 [ 12.98589371 -10.87801011] -0.42391872020081967 47 343.230404987148 0.6910299003322259 [ 13.04892373 -11.00707968] -0.8077020039923326 48 341.9670465305152 0.6926910299003323 [ 13.15705936 -11.10826813] -0.7412950657179342 49 345.00737657297736 0.6777408637873754 [ 13.2791234 -11.18406515] -0.42419177050567947 50 341.9200096395182 0.6926910299003323 [ 13.33638984 -11.29960241] -0.7717745803621642 51 349.3836845856781 0.7026578073089701 [ 13.39744739 -11.40768015] -1.0292790317479588 52 344.4903632983186 0.6976744186046512 [ 13.50072171 -11.48671441] -0.9092559553195997 53 340.7574068208695 0.6960132890365448 [ 13.6123208 -11.55988726] -0.6935532610739639 54 340.805386624196 0.6993355481727574 [ 13.68639987 -11.65153496] -0.7342895514020545 55 340.49392788694547 0.6910299003322259 [ 13.76801887 -11.73178611] -0.6637912463234132 56 341.9525612393154 0.6827242524916943 [ 13.85607239 -11.80401184] -0.5244038782727635 57 342.4601952391535 0.6910299003322259 [ 13.88831271 -11.90410566] -0.8707665006891648 58 348.956902760427 0.7009966777408638 [ 13.93166659 -11.99764468] -1.0586961821957064 59 341.4277161072633 0.6810631229235881 [ 14.04778436 -12.04046736] -0.5395897877205655 60 340.61104785487146 0.6926910299003323 [ 14.09417366 -12.13339773] -0.7923535054980428 61 340.74739145489065 0.6843853820598007 [ 14.17792347 -12.19588362] -0.5717686517679978 62 341.67127740851623 0.6910299003322259 [ 14.21558263 -12.28588058] -0.8674610974713537 63 339.72149643227976 0.7009966777408638 [ 14.29434558 -12.34332817] -0.7233292317740916 64 341.7372580235468 0.6910299003322259 [ 14.33280419 -12.42693673] -0.8810879467702697 65 339.51753364507874 0.6910299003322259 [ 14.40660021 -12.48591675] -0.690307536746365 66 341.2876029803096 0.6810631229235881 [ 14.47693401 -12.5391267 ] -0.5276229218814223 67 341.2693625858884 0.6910299003322259 [ 14.50278134 -12.62721911] -0.8749864297093192 68 339.810130328162 0.6893687707641196 [ 14.58207819 -12.67254054] -0.6124870186094366 69 344.89124145826287 0.6827242524916943 [ 14.65396518 -12.72162865] -0.4029288540095109 70 339.7700262715683 0.6943521594684385 [ 14.66501406 -12.80671299] -0.8020333923220707 71 339.1435910668182 0.6910299003322259 [ 14.72670334 -12.85627644] -0.6886987617119359 72 345.03957223958525 0.7043189368770764 [ 14.73329231 -12.93372104] -1.016725878454925 73 340.11365652333814 0.6926910299003323 [ 14.7950637 -12.98445056] -0.8400323934010566 74 344.4938153667252 0.6794019933554817 [ 14.89331145 -13.02159439] -0.4105316186383425 75 344.189283596777 0.6777408637873754 [ 14.95333295 -13.07292574] -0.42015750399718416 76 340.5157373458087 0.6943521594684385 [ 14.95149023 -13.15674832] -0.8762495868911429 77 338.8434386579289 0.6960132890365448 [ 15.01018125 -13.20118306] -0.7351465625232946 78 339.028510247146 0.6893687707641196 [ 15.06349586 -13.25179768] -0.6503859841371638 79 358.5176962016868 0.6843853820598007 [ 15.03270124 -13.34095515] -1.2836674665954704 80 352.1335356786034 0.6744186046511628 [ 15.17463278 -13.33475856] -0.24817255074714198 81 339.490802311773 0.686046511627907 [ 15.17181711 -13.40465993] -0.5994159120383523 82 339.296957991388 0.6877076411960132 [ 15.20932905 -13.4512126 ] -0.6120924210591328 83 338.71690036767154 0.6943521594684385 [ 15.24516372 -13.50803212] -0.6712122285827052 84 338.80628059142776 0.6976744186046512 [ 15.27359186 -13.56054184] -0.7829227345250828 85 341.7444376114255 0.6777408637873754 [ 15.34152971 -13.59104929] -0.49038590309169655 86 343.89350855796033 0.6777408637873754 [ 15.3783545 -13.63559263] -0.42271511999803635 87 338.4871863433057 0.6976744186046512 [ 15.37257148 -13.69838491] -0.7392099347017013 88 338.4596985325752 0.6926910299003323 [ 15.40143573 -13.74668821] -0.6985971898182785 89 338.4389726934747 0.6976744186046512 [ 15.42498785 -13.79487073] -0.7408236782441413 90 340.87318602593257 0.6760797342192691 [ 15.48091521 -13.82616514] -0.5174789721934601 91 338.52192870054034 0.6926910299003323 [ 15.49522945 -13.87257611] -0.6683793303055979 92 338.4587306222692 0.6976744186046512 [ 15.51819368 -13.92063485] -0.7653602224598918 93 341.01234445716995 0.6727574750830565 [ 15.57476183 -13.94465718] -0.5109056225188413 94 340.09467160438123 0.6943521594684385 [ 15.55718172 -14.00586951] -0.8927194485609143 95 339.84910626934 0.6943521594684385 [ 15.59042484 -14.04635578] -0.8824234955579126 96 338.60096103902424 0.6976744186046512 [ 15.62162756 -14.07667043] -0.7969610157728395 97 346.3745162773995 0.6843853820598007 [ 15.69837933 -14.08539705] -0.3567764710573505 98 338.5160107125221 0.6926910299003323 [ 15.69021749 -14.14398478] -0.6522016586237613 99 338.3798921196803 0.7009966777408638 [ 15.71372364 -14.19256249] -0.7782638741367814
Un peu de visu supplémentaire :
Le trajet fait par $θ$ au cours de l'apprentissage
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20, 20), dpi=200)
ax = plt.axes(projection='3d')
x, y, z = np.hsplit(np.array(theta_history), 3)
ax.plot(x.squeeze(), y.squeeze(), z.squeeze(), label="Trajet de $θ$ au cours de l'apprentissage")
ax.legend()
plt.show()
def make_vector_corpus(featurized_corpus):
vector_corpus = np.stack([*featurized_corpus["pos"], *featurized_corpus["neg"]])
vector_target = np.concatenate([np.ones(len(featurized_corpus["pos"])), np.zeros(len(featurized_corpus["neg"]))])
return vector_corpus, vector_target
vector_corpus, vector_target = make_vector_corpus(imdb_features)
w1 = np.linspace(-50, 100, 200)
w2 = np.linspace(-100, 50, 200)
W1, W2 = np.meshgrid(w1, w2)
W = np.stack((W1, W2), axis=-1)
# Un peu de magie pour accélérer le calcul
confidence = logistic(
np.einsum("ijn,kn->ijk", W, vector_corpus)
)
broadcastable_target = vector_target[np.newaxis, np.newaxis, :]
loss = -np.log(confidence * broadcastable_target + (1-confidence)*(1-broadcastable_target)).sum(axis=-1)
fig = plt.figure(figsize=(20, 20), dpi=200)
ax = plt.axes(projection='3d')
ax.set_xlim(-50, 100)
ax.set_ylim(-100, 50)
ax.set_zlim(0, 3000)
surf = ax.plot_surface(W1, W2, loss, cmap=tc.tol_cmap("sunset"), edgecolor="none", rstride=1, cstride=1, alpha=0.8)
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.plot_wireframe(W1, W2, loss, color='black')
heatmap = ax.contourf(W1, W2, loss, offset=-30, cmap=tc.tol_cmap("sunset"))
plt.title("Paysage de la fonction de coût en fonction des valeurs de $w$ pour $b=0$")
plt.show()
Un dernier point : on a vu dans tout ceci comment utiliser la régression logistique pour un problème de classification à deux classes. Comment on l'étend à $n$ classes ?
Réfléchissons déjà à quoi ressemblerait la sortie d'un tel classifieur :
Pour un problème à deux classes, le classifieur $g$ nous donne pour chaque exemple $x$ une estimation $g(x)$ de la vraisemblance de la classe $1$, et on a vu que la vraisemblance de la classe $0$ était nécessairement $1-g(x)$ pour que la somme des vraisemblances fasse 1.
On peut le présenter autrement : considérons le classifieur $f$ tel que pour tout exemple $x$
$$f(x) = (1-g(x), g(x))$$$f$ nous donne un vecteur à deux coordonnées, $f_0(x)$ et $f_1(x)$, qui sont respectivement les vraisemblances des classes $0$ et $1$.
Pour un problème à $n$ classes, on va vouloir une vraisemblance par classe, on va donc procéder de la façon suivante :
On considère des poids $(w_1, b_1), …, (w_n, b_n)$. Ils définissent un classifieur linéaire.
En effet, si on considère les $z_i$ définis pour tout exemple $x$ par
$$ \begin{cases} z_1 = w_1⋅x + b_1\\ \vdots\\ z_n = w_n⋅x + b_1 \end{cases} $$On peut choisir la classe $y$ à affecter à $x$ en prenant $y=\operatorname{argmax}\limits_i z_i$
Il reste à normaliser pour avoir des vraisemblances. Pour ça on utilise une fonction très importante : la fonction $\operatorname{softmax}$, définie ainsi :
$$\operatorname{softmax}(z_1, …, z_n) = \left(\frac{e^{z_1}}{\sum_i e^{z_i}}, …, \frac{e^{z_n}}{\sum_i e^{z_i}}\right)$$Contrairement à la fonction logistique qui prenait un nombre en entrée et renvoyait un nombre, $\operatorname{softmax}$ prend en entrée un vecteur non-normalisé et renvoie un vecteur normalisé.
On définit enfin le classifieur logistique multinomial $f$ de la façon suivante : pour tout exemple $x$, on a
$$f(x) = \operatorname{softmax}(w_1⋅x+b_1, …, w_n⋅x+b_n) = \left(\frac{e^{w_1⋅x+b_1}}{\sum_i e^{w_i⋅x+b_i}}, …, \frac{e^{w_n⋅x+b_n}}{\sum_i e^{w_i⋅x+b_i}}\right)$$et on choisit pour $x$ la classe
$$y = \operatorname{argmax}\limits_i f_i(x) = \operatorname{argmax}\limits_i \frac{e^{w_i⋅x+b_i}}{\sum_j e^{w_j⋅x+b_j}}$$Comme la fonction exponentielle est croissante, ce sera la même classe que le classifieur linéaire précédent. Comme pour le cas à deux classe, la différence se fera lors de l'apprentissage. Je vous laisse aller en lire les détails dans Speech and Language Processing, mais l'idée est la même : on utilise la log-vraisemblance négative de la classe correcte comme fonction de coût, et on optimise les paramètres avec l'algo de descente de gradient stochastique.
Un dernier détail ?
Qu'est-ce qui se passe si on prend ce qu'on vient de voir pour $n=2$ ? Est-ce qu'on retombe sur le cas à deux classe vu précédemment ?
Oui, regarde : dans ce cas
$$ \begin{align} f_1(x) &= \frac{e^{w_1⋅x+b_1}}{e^{w_0⋅x+b_0}+e^{w_1⋅x+b_1}}\\ &= \frac{1}{ \frac{e^{w_0⋅x+b_0}}{e^{w_1⋅x+b_1}} + 1 }\\ &= \frac{1}{e^{(w_0⋅x+b_0)-(w_1⋅x+b_1)} + 1}\\ &= \frac{1}{1 + e^{(w_0-w_1)⋅x+(b_0-b_1)}}\\ &= σ((w_0-w_1)⋅x+(b_0-b_1)) \end{align} $$Autrement dit, appliquer ce qu'on vient de voir pour le cas multinomial, si $n=2$, c'est comme appliquer ce qu'on a vu pour deux classes, avec $w=w_0-w_1$ et $b=b_0-b_1$.
Vous êtes arrivé⋅e⋅s au bout de ce cours et vous devriez avoir quelques idées de plusieurs concepts importants :
On reparlera de tout ça en temps utile. Pour la suite de vos aventures au pays des classifieurs logistiques, je vous recommande plutôt d'utiliser leur implémentation dans scikit-learn. Maintenant que vous savez comment ça marche, vous pouvez le faire la tête haute. Bravo !
Vous avez aussi découvert les premiers réseaux de neurones de ce cours et ce n'est pas rien !